In one of our previous article, we have mentioned about how to read JSON in C# and how to open and read XML in C#, now in this article, we will be providing you working example of converting JSON to XML and XML to JSON using C#, which can be very useful when exchanging data between different services.

For this article, we will be using Console Application example, but you can use the same C# code in ASP.NET MVC or Web-Form or even in .NET Core.

So, first of all we will create a new Console Application in Visual Studio, open your Visual Studio and then navigate to File -> New -> Project -> Select "Windows Desktop" from left pane and "Console App (.NET Framework)" from right-pane, name it as "XMLtoJSONAndJSONToXML" and click "OK"

convert-json-to-xml-and-xml-to-json-csharp.png

Convert XML to JSON in C#

We will be using Newtonsoft.Json NuGet package for this, so we would have to install it using Nuget first, so open Nuget package manager console by navigating to "Tools" -> "Nuget Package Manager" -> "Package manager console" and copy/paste the below command and hit "Enter"

Install-Package Newtonsoft.Json

Once you installed, the Newtonsoft.Json package, we will be the below sample XML to convert it on JSON.

Considering we have sample XML as below

<?xml version='1.0'?>
<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>
   <book id='bk102'>
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>  
</catalog>

Here is the C# code to convert XML to JSON using Newtonsoft.Json's method "JsonConvert.SerializeXmlNode(XML,FormattingIndetation)"

using Newtonsoft.Json;
using System;
using System.Xml;

namespace XMLtoJSONAndJSONToXML
{
    class Program
    {
        

        static void Main(string[] args)
        {
            var xml = @"<?xml version='1.0'?>
<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>
   <book id='bk102'>
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>  
</catalog>
";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            string jsonText = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);

            Console.WriteLine(jsonText);
        }
    }
}

Output:

{
  "?xml": {
    "@version": "1.0"
  },
  "catalog": {
    "book": [
      {
        "@id": "bk101",
        "author": "Gambardella, Matthew",
        "title": "XML Developer's Guide",
        "genre": "Computer",
        "price": "44.95",
        "publish_date": "2000-10-01",
        "description": "An in-depth look at creating applications \r\n      with XML."
      },
      {
        "@id": "bk102",
        "author": "Ralls, Kim",
        "title": "Midnight Rain",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2000-12-16",
        "description": "A former architect battles corporate zombies, \r\n      an evil sorceress, and her own childhood to become queen \r\n      of the world."
      }
    ]
  }
}

xml-to-json-csharp-min.png

Attribute to force JSON conversion

You can also use Custom attributes in your XML, so while converting XML to JSON, you can force Newtonsoft.Json to convert it into array

For example, if you have below XML as shown in XML, then you will see different output

xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
  <name>Vikas</name>
  <url>http://www.qawithexperts.com</url>
  <role json:Array='true'>Developer</role>
</person>";

then complete C# code for converting into JSON can be

using Newtonsoft.Json;
using System;
using System.Xml;

namespace XMLtoJSONAndJSONToXML
{
    class Program
    {
        

        static void Main(string[] args)
        {
            var xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
  <name>Vikas</name>
  <url>https://qawithexperts.com</url>
  <role json:Array='true'>Developer</role>
</person>";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            string jsonText = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);

            Console.WriteLine(jsonText);
        }
    }
}

Output:

{
  "person": {
    "@id": "1",
    "name": "Vikas",
    "url": "https://qawithexperts.com",
    "role": [
      "Developer"
    ]
  }
}

Convert JSON to XML using C#

Now, we will try to convert JSON into XML using C#, we will still use Newtonsoft.Json, which can be helpful in this case also.

But in this case we will be using "JsonConvert.DeserializeXmlNode" method to convert JSON back to XML

So, considering below JSON sample

{
  '?xml': {
    '@version': '1.0',
    '@standalone': 'no'
  },
  'root': {
    'books': [
      {
        '@id': 'bk101',
        'author': 'Gambardella, Matthew',
        'title': 'XML Developer's Guide',
        'price': '44.95',
      },
      {
        '@id': 'bk102',
        'author': 'Ralls, Kim',
        'title': 'Midnight Rain',
        'price': '5.95',
      }
    ]
  }
}

We can have C# code as below

using Newtonsoft.Json;
using System;
using System.Xml;

namespace XMLtoJSONAndJSONToXML
{
    class Program
    {        
        static void Main(string[] args)
        {
            string json = @"{
  '?xml': {
    '@version': '1.0',
    '@standalone': 'no'
  },
  'books': {
    'book': [
      {
        '@id': 'bk101',
        'author': 'Gambardella, Matthew',
        'title': 'XML Developer\'s Guide',
        'price': '44.95',
      },
      {
        '@id': 'bk102',
        'author': 'Ralls, Kim',
        'title': 'Midnight Rain',
        'price': '5.95',
      }
    ]
  }
}";
            XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

            Console.WriteLine(doc.OuterXml);
        }
    }
}

json-to-xml-csharp-min.png

JSON to XML OR XML to JSON in C# without using Newtonsoft.Json

If you don't want to use Newtonsoft.Json Nuget package, then you can still convert JSON to XML and Vice-versa using C#.

Before we check for code, in your console application, you would have to add 2 Reference, so right-click on "Reference" and then search for "System.Web.Extensions" and "System.Runtime.Serialization"

Once you have added both of these Reference, you can use the below sample code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Script.Serialization;
using System.Xml;
using System.Xml.Linq;

namespace XMLtoJSONAndJSONToXML
{
    class Program
    {
       
        static void Main(string[] args)
        {
            string json = "{\"name\":\"John\", \"age\":31, \"city\":\"New York\"}";
            var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
    Encoding.ASCII.GetBytes(json), new XmlDictionaryReaderQuotas()));


            Console.WriteLine("JSON to XML");
            Console.WriteLine(xml);
            Console.WriteLine();
            Console.WriteLine();

            var BacktoJSON = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xml.ToString())));
            Console.WriteLine("XML to JSON");
            Console.WriteLine(BacktoJSON);

        }


        private static Dictionary<string, object> GetXmlData(XElement xml)
        {
            var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
            if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
            else if (!xml.IsEmpty) attr.Add("_value", xml.Value);

            return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
        }

    }
}

Output:

JSON to XML
<root type="object">
  <name type="string">John</name>
  <age type="number">31</age>
  <city type="string">New York</city>
</root>


XML to JSON
{"root":{"type":"object","_value":[{"name":{"type":"string","_value":"John"}},{"age":{"type":"number","_value":"31"}},{"city":{"type":"string","_value":"New York"}}]}}

json-to-xml-and-xml-to-json-csharp-min.png

Which method to use?

I will recommend using Newtonsoft.Json, as this Nuget package makes conversion more easier than custom one and for large projects it is better to use this extensively used Library.

You may also like to read:

Useful Visual Studio Extensions (Plugins), every developer should use.

Convert JSON to XML Online

Convert XML to JSON online