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

Posted by Anuraj on Monday, December 9, 2013 Reading time :1 minute

.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>" +

var doc = new XmlDocument();

var jsonText = JsonConvert.SerializeXmlNode(doc);

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;

Happy Programming :)

What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.

Similar Posts

Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon

BMC logoBuy me a coffee

Copyright © 2019 - Anuraj P. 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. Hosted with ❤ by GitHub