Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid the ROOT Element when parsing from XML to JSON in C#

I am trying to create a JSON from an xml using JSON.NET

XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson); //xmlPerson is the xml from above
JObject personDefinition = JObject.Parse(JsonConvert.SerializeObject(docPerson));
Tasks.personDefinition = personDefinition["personDefinition"];

OUTPUT JSON

"person":{"person":[{"personId":"1","firstName":"Name1","lastName":"lastName1"},                  {"personId":"3","firstName":"Name2","lastName":"lastName2"}]}

I don't need the outer person and just need the following json

REQUIRED JSON

"person":[{"personId":"1","firstName":"1","lastName":"Weight"},{"personId":"3","firstName":"4","lastName":"Pulse Ox"}]}

I have tried using the .first method however it is throwing an error. Can anyone suggest on how to strip the root from the output json

like image 559
user2515186 Avatar asked Oct 11 '13 06:10

user2515186


1 Answers

JSON.Net has a SerializeXmlNode() method that can do exactly what you want. Simply pass true to the omitRootObject parameter. Observe:

string xmlPerson = @"<PersonDefinition><Person><name>Nicolas</name><age>22</age></Person><Person><name>Pankaj</name><age>25</age></Person></PersonDefinition>";
XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson);
string json = JsonConvert.SerializeXmlNode(docPerson, Formatting.None, true);
Console.WriteLine(json);

Output:

{"Person":[{"name":"Nicolas","age":"22"},{"name":"Pankaj","age":"25"}]}
like image 53
Brian Rogers Avatar answered Oct 02 '22 15:10

Brian Rogers