Wednesday, November 5, 2014

Cast XML directly to JSON in C#.

This suggests this:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

 
 

...which seems to work just dandy. If Visual Studio seems not to recognize .SerializeXmlNode then you probably need the latest Newtonsoft from NuGet like so:

Install-Package Newtonsoft.Json

 
 

Also, casting back to XML from JSON is even easier. Behold:

XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

 
 

...as suggested in the link at the top of this posting works great.

No comments:

Post a Comment