Sai A Sai A
Updated date Jul 29, 2023
In this blog, we explore various methods to convert JSON to XML in C#. From the popular Newtonsoft.Json library to built-in .NET classes like DataContractJsonSerializer and the high-performance System.Text.Json.
  • 3.5k
  • 0
  • 0

Introduction:

Data exchange formats like JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are fundamental for communication between applications and services. JSON's lightweight nature and simplicity have made it a popular choice, but XML remains relevant in various industries and legacy systems. The need to convert data between these formats is a common task, and in this blog, we will explore how to convert JSON to XML in C#.

Method 1: Using Newtonsoft.Json and XmlDocument

The first method involves using the popular Newtonsoft.Json library to parse JSON data and the built-in XmlDocument class to create XML. This method is suitable when you have JSON data in a string format or a file.

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

class Program
{
    static void Main()
    {
        // Sample JSON data
        string jsonData = "{ \"name\": \"John\", \"age\": 30, \"city\": \"New York\" }";

        // Using Newtonsoft.Json to deserialize JSON
        dynamic jsonObject = JsonConvert.DeserializeObject(jsonData);

        // Creating an XmlDocument and adding root element
        XmlDocument xmlDocument = new XmlDocument();
        XmlNode rootNode = xmlDocument.CreateElement("Root");
        xmlDocument.AppendChild(rootNode);

        // Adding elements and attributes from JSON data
        foreach (var property in jsonObject)
        {
            XmlNode node = xmlDocument.CreateElement(property.Name);
            node.InnerText = property.Value.ToString();
            rootNode.AppendChild(node);
        }

        // Output the XML
        string xmlOutput = xmlDocument.OuterXml;
        Console.WriteLine(xmlOutput);
    }
}

Output:

<Root>
  <name>John</name>
  <age>30</age>
  <city>New York</city>
</Root>

Method 2: Using DataContractJsonSerializer and XElement

The second method involves using the DataContractJsonSerializer class to parse JSON data and XElement to create XML. This approach is suitable when you prefer working with built-in .NET classes.

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

class Program
{
    static void Main()
    {
        // Sample JSON data
        string jsonData = "{ \"name\": \"John\", \"age\": 30, \"city\": \"New York\" }";

        // Using DataContractJsonSerializer to deserialize JSON
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData)))
        {
            var serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
            var jsonObject = (Dictionary<string, object>)serializer.ReadObject(stream);

            // Creating XElement and adding elements and attributes
            XElement xmlElement = new XElement("Root",
                jsonObject.Select(kv => new XElement(kv.Key, kv.Value))
            );

            // Output the XML
            string xmlOutput = xmlElement.ToString();
            Console.WriteLine(xmlOutput);
        }
    }
}

Output:

<Root>
  <name>John</name>
  <age>30</age>
  <city>New York</city>
</Root>

Method 3: Using System.Text.Json and XDocument

The third method involves using System.Text.Json (introduced in .NET Core 3.0 and .NET 5.0) to parse JSON data and XDocument to create XML.

using System;
using System.Text.Json;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        // Sample JSON data
        string jsonData = "{ \"name\": \"John\", \"age\": 30, \"city\": \"New York\" }";

        // Using System.Text.Json to parse JSON
        JsonDocument jsonDocument = JsonDocument.Parse(jsonData);

        // Creating XDocument and adding elements and attributes
        XDocument xDocument = new XDocument(
            new XElement("Root",
                jsonDocument.RootElement.EnumerateObject()
                    .Select(prop => new XElement(prop.Name, prop.Value.ToString()))
            )
        );

        // Output the XML
        string xmlOutput = xDocument.ToString();
        Console.WriteLine(xmlOutput);
    }
}

Output:

<Root>
  <name>John</name>
  <age>30</age>
  <city>New York</city>
</Root>

Conclusion:

In this blog, we explored various methods to convert JSON to XML in C#. We started with Newtonsoft.Json and XmlDocument, which offer flexibility and ease of use, making them excellent choices for most scenarios. We then explored using DataContractJsonSerializer and XElement, a combination of built-in .NET classes, which might be preferred in certain environments. Finally, we discussed the option, System.Text.Json, which provides high performance and comes with .NET Core 3.0 and later versions. Its integration with XDocument makes it a compelling choice for developers aiming to leverage the latest .NET features.

Comments (0)

There are no comments. Be the first to comment!!!