Convert XElements to Json

You need to capture the data type in a class that is serializable.
In this example I use Employee to do so. The first action will be to construct an IEnumerable of Employee:

 XElement empXml = GetEmployees();
var empJson = from emp in empXml.Descendants("Employee")
select new Employee
ID = emp.Element("ID").Value,
FirstName = emp.Element("FirstName").Value,
Department = emp.Element("Department").Value,
City = emp.Element("City").Value

The second step is to serialize the enumeration into the memory stream.

  var ser = new  DataContractJsonSerializer(typeof(IEnumerable));
var ms = new MemoryStream();
ser.WriteObject(ms, empJson);

And at last, we can take the generated stream as a string just before closing the stream.

string json = Encoding.Default.GetString(ms.ToArray());

Author: Pouya Panahy

Microsoft certified DevOps engineer with passion in analysing, designing and implementing solutions for Azure Cloud with hands-on experience in security and quality assurence.

Leave a Reply