Convert XML to Json and remove XML declaration from converted Json

I have the following XML file that I need to convert to JSON. I can convert it to Json using the Newtonsoft library, but also includes part of the xml declaration. How can I skip the xml declaration part and convert the remaining file to json?

I use the code below (C #) to convert it.

JsonConvert.SerializeXmlNode(employeeXMLDoc) 

Xml input example

 <?xml version="1.0" encoding="UTF-8" ?> <Employee> <EmployeeID>1</EmployeeID> <EmployeeName>XYZ</EmployeeName> </Employee> 

Json output

 {"?xml":{"@version":"1.0","@encoding":"UTF-8"},"Employee":{"EmployeeID":"1","EmployeeName":"XYZ"}} 
+5
source share
2 answers

You can remove the first child from the XmlDocument :

 employeeXMLDoc.RemoveChild(employeeXMLDoc.FirstChild); 

And then we serialize how you are doing now.

+5
source

Or in one line:

JsonConvert.SerializeXmlNode(employeeXMLDoc.FirstChild.NextSibling);

+1
source

Source: https://habr.com/ru/post/1208239/


All Articles