Convert XML to JSON in C#

By FoxLearn 1/10/2025 2:17:20 AM   69
To convert XML to JSON using ExpandoObject, XDocument, and Newtonsoft.Json in C#, follow these steps:

Let’s say you’re receiving XML feeds from a client, but you need to enrich the data before using it. Plus, you prefer working with JSON.

Example XML Input:

<products>
    <product>
        <title>January 2024</title>
        <link><![CDATA[https://example.com/2024/01/]]></link>
    </product>
    <product>
        <title>February 2024</title>
        <link><![CDATA[https://example.com/2024/02/]]></link>
    </product>
    <product>
        <title>March 2024</title>
        <link><![CDATA[https://example.com/2024/03/]]></link>
    </product>
</products>

Desired Output (Enriched JSON):

[
    {
        "title": "Special Blog Post from January 2024",
        "url": "https://example.com/2024/01/"
    },
    {
        "title": "Special Blog Post from February 2024",
        "url": "https://example.com/2024/02/"
    },
    {
        "title": "Special Blog Post from March 2024",
        "url": "https://example.com/2024/03/"
    }
]

First, We parse the XML using XDocument.Parse(xmlContent) to load the XML into an XDocument object.

using Newtonsoft.Json;
using System;
using System.Dynamic;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

namespace XMLToJsonExample
{
    public class XMLConverter
    {
        // Method to convert XML to JSON
        public string ConvertXMLToJson(string xmlContent)
        {
            // Create a dynamic list for the JSON output
            dynamic output = new List<dynamic>();

            try
            {
                // Parse the XML content into an XDocument object
                var document = XDocument.Parse(xmlContent);

                // Retrieve all product elements from the XML
                var products = document.Descendants("product");

                foreach (var product in products)
                {
                    // Create a dynamic object (ExpandoObject) for each product
                    dynamic row = new ExpandoObject();

                    // Enrich the title and get the link
                    row.title = "Special Blog Post from " + product.Element("title")?.Value;
                    row.url = product.Element("link")?.Value;

                    // Add the dynamic row to the output list
                    output.Add(row);
                }

                // Serialize the dynamic list to a JSON string
                string jsonResult = JsonConvert.SerializeObject(output, Formatting.Indented);
                return jsonResult;
            }
            catch (Exception ex)
            {
                throw new Exception($"Error converting XML to JSON: {ex.Message}", ex);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string xmlData = "input your xml data above";

            // Create an instance of XMLConverter and call the ConvertXMLToJson method
            var converter = new XMLConverter();
            string jsonOutput = converter.ConvertXMLToJson(xmlData);

            // Output the resulting JSON
            Console.WriteLine(jsonOutput);
        }
    }
}

In this example:

  • The Descendants("product") method retrieves all <product> elements in the XML.
  • For each <product> element, we create a new ExpandoObject which allows us to add properties dynamically.
  • In this case, we enrich the title by prepending "Special Blog Post from " to the existing value, and extract the url from the <link> element.
  • The JsonConvert.SerializeObject(output, Formatting.Indented) converts the dynamic list of objects into a formatted JSON string.