Sai A Sai A
Updated date Jul 29, 2023
In this blog, we explore different methods to convert XML data to JSON in C# - a common requirement in modern software development for data interchange. We delve into two popular libraries, Newtonsoft.Json and System.Text.Json, providing step-by-step explanations and C# programs for each method.
  • 2.9k
  • 0
  • 0

Introduction:

Interchanging data between various systems is a frequent necessity in modern software development. To accomplish this task, XML and JSON serve as two widely used data formats. Sometimes, there arises a need to convert XML data into JSON format to ensure seamless compatibility and smooth integration. In this blog, we will explore different methods to achieve this conversion using C#.

Method 1: Using Newtonsoft.Json Library

Newtonsoft.Json, also known as Json.NET, is a powerful library for working with JSON data in C#. It provides methods for both serialization and deserialization, making it a popular choice among developers. Let's see how we can convert XML to JSON using Newtonsoft.Json.

using Newtonsoft.Json;
using System;

public class XmlToJsonConverter
{
    public static string ConvertXmlToJson(string xml)
    {
        try
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(xml);
            string json = JsonConvert.SerializeXmlNode(xmlDoc);
            return json;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error occurred: " + ex.Message);
            return string.Empty;
        }
    }
}

Output using Newtonsoft.Json:

string xmlData = "<root><name>John</name><age>30</age></root>";
string jsonOutput = XmlToJsonConverter.ConvertXmlToJson(xmlData);
Console.WriteLine(jsonOutput);
Output:
{
  "root": {
    "name": "John",
    "age": "30"
  }
}

Method 2: Using System.Text.Json Library (Available in .NET Core 3.0+)

With the introduction of .NET Core 3.0, the System.Text.Json namespace was added, providing built-in JSON support. This library is lightweight and designed for high-performance scenarios. Let's explore how to convert XML to JSON using System.Text.Json.

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Xml;

public class XmlToJsonConverter
{
    public static string ConvertXmlToJson(string xml)
    {
        try
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            var jsonElement = XmlNodeToJsonElement(xmlDoc.DocumentElement);
            return JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error occurred: " + ex.Message);
            return string.Empty;
        }
    }

    private static JsonElement XmlNodeToJsonElement(XmlNode node)
    {
        var jsonObject = new Dictionary<string, JsonElement>();

        if (node.Attributes != null)
        {
            foreach (XmlAttribute attr in node.Attributes)
            {
                jsonObject[attr.Name] = JsonDocument.Parse($"\"{attr.Value}\"").RootElement;
            }
        }

        foreach (XmlNode childNode in node.ChildNodes)
        {
            if (childNode.NodeType == XmlNodeType.Element)
            {
                if (jsonObject.ContainsKey(childNode.Name))
                {
                    if (jsonObject[childNode.Name].ValueKind == JsonValueKind.Array)
                    {
                        ((List<JsonElement>)jsonObject[childNode.Name].Value).Add(XmlNodeToJsonElement(childNode));
                    }
                    else
                    {
                        jsonObject[childNode.Name] = new List<JsonElement> { jsonObject[childNode.Name], XmlNodeToJsonElement(childNode) };
                    }
                }
                else
                {
                    jsonObject[childNode.Name] = XmlNodeToJsonElement(childNode);
                }
            }
            else if (childNode.NodeType == XmlNodeType.Text)
            {
                jsonObject[childNode.ParentNode.Name] = JsonDocument.Parse($"\"{childNode.InnerText}\"").RootElement;
            }
        }

        return new JsonElement(jsonObject);
    }
}

Output using System.Text.Json:

string xmlData = "<root><name>John</name><age>30</age></root>";
string jsonOutput = XmlToJsonConverter.ConvertXmlToJson(xmlData);
Console.WriteLine(jsonOutput);
Output:
{
  "root": {
    "name": "John",
    "age": "30"
  }
}

Conclusion:

In this blog, we explored different methods to convert XML to JSON in C# - using Newtonsoft.Json and System.Text.Json libraries. While Newtonsoft.Json is a widely-used library known for its ease of use, System.Text.Json offers native JSON support in .NET Core 3.0+ and is designed for high performance.

Comments (0)

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