Thursday, November 24, 2016

XML to JSON tricks using C#.NET and Newtonsoft JSON Library


// Converting XML to JSON
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Temp\\SampleData.xml");    // Use this line to load XML from file.           
doc.LoadXml(fullXmlContent); // Use this line if there is already XML content in a string.
string jsonText = JsonConvert.SerializeXmlNode(doc);
JObject dataFromSQL = (JObject) JsonConvert.DeserializeObject(jsonText);
 
// At this point the XML is converted to JSON object.
 
//Get Agency Data from JSON object. Assuming "Agency" element is contained inside "MajorAccounts" element.
 
if (dataFromSQL["MajorAccounts"]["Agency"] == null)
throw new Exception("Data missing in XML for [MajorAccounts][Agency].");
 
JObject agencyJObject = (JObject)dataFromSQL["MajorAccounts"]["Agency"] ;
               
Hope this helps !
 
Cheers
Adam

No comments:

Post a Comment

All Blogs so far ...