How to convert JSON to XML and vice versa in C#

December 09, 2013 by Anuraj

.Net .Net 4.0 ASP.Net Javascript Silverlight

Json.NET supports converting JSON to XML and vice versa using the XmlNodeConverter. The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it to JSON text.

string xml = @"<catalog><book id=""bk101"">" +
    "<author>Gambardella, Matthew</author>" +
    "<title>XML Developer's Guide</title>" +
    "<genre>Computer</genre>" +
    "<price>44.95</price>" +
    "<publish_date>2000-10-01</publish_date>" +
    "<description>An in-depth look at " +
                "creating applications with XML.</description>" +
"</book>" +
"</catalog>";

var doc = new XmlDocument();
doc.LoadXml(xml);

var jsonText = JsonConvert.SerializeXmlNode(doc);
Console.WriteLine(jsonText);

The second helper method on JsonConvert is DeserializeXmlNode(). This method takes JSON text and deserializes it into a XmlNode.

var xmlNode = JsonConvert.DeserializeXmlNode(jsonText).OuterXml;
Console.WriteLine(xmlNode);

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub