Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XML to Json and remove XML declaration from converted Json

Tags:

json

xml

json.net

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

I am using below code(C#) to convert it.

JsonConvert.SerializeXmlNode(employeeXMLDoc)

Sample xml input

<?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"}}
like image 542
RAHUL Avatar asked Dec 03 '14 13:12

RAHUL


2 Answers

You could remove the first child from the XmlDocument:

employeeXMLDoc.RemoveChild(employeeXMLDoc.FirstChild);

And then serialize as you're doing now.

like image 170
Andrew Whitaker Avatar answered Dec 18 '22 08:12

Andrew Whitaker


Or in a single line:

JsonConvert.SerializeXmlNode(employeeXMLDoc.FirstChild.NextSibling);

like image 31
Mr. Bungle Avatar answered Dec 18 '22 07:12

Mr. Bungle