Quantcast
Channel: briancaos – Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 276

C# Convert XML to JSON using dynamic ExpandoObject, XDocument and NewtonSoft.JSON

$
0
0

So I receive these XML feeds from my client, but I need to enrich the contents before I can use the data. AND I would like to work with JSON instead.

So how to do that with a few lines of code?

Image this imaginary XML input:

<products>
    <product>
        <title>June 2023</title>
        <link><![CDATA[https://briancaos.wordpress.com/2023/06/]]></link>
    </product>
    <product>
        <title>May 2023</title>
        <link><![CDATA[https://briancaos.wordpress.com/2023/05/]]></link>
    </product>
    <product>
        <title>April 2023</title>
        <link><![CDATA[https://briancaos.wordpress.com/2023/04/]]></link>
    </product>
</products>

And I wish to convert this into a JSON array + enrich the title:

[
    {
        "title": "Blog Posts from June 2023",
        "url": "https://briancaos.wordpress.com/2023/06/"
    },
    {
        "title": "Blog Posts from May 2023",
        "url": "https://briancaos.wordpress.com/2023/05/"
    },
    {
        "title": "Blog Posts from April 2023",
        "url": "https://briancaos.wordpress.com/2023/04/"
    }
]

The process can be done this way:

  • Read the XML document using XDocument
  • Iterate over each “product” item, creating dynamic ExpandoObject rows
  • Serialize the dynamic list using NewtonSoft.JSON

THE CODE:

using Newtonsoft.Json;
using System.Dynamic;
using System.Globalization;
using System.Xml.Linq;

namespace MyCode
{
  public class MyClass
  {
    // Method accepts the XML as a string
    public string ConvertXMLToJson(string feedContent)
    {
      // This dynamic array is the output
      dynamic output = new List<dynamic>();
      try
      { 
        // Read the XML document into the XDocument variable
        var document = XDocument.Parse(feedContent);
        // Grab all XML items called "product"
        // and iterate over them
        var items = document.Descendants().Where(node => node.Name == "product");
        foreach (var item in items)
        {
          // Create a new row for the output array
          dynamic row = new ExpandoObject();
          // Add the fields of the dynamic object
          row.title = "Blog Posts from " + item.Element("title").Value;
          row.url = item.Element("link").Value;
          // Add the row to the output
          output.Add(row);
        }
        // Serialize the dynamic array to a JSON string
        string outputJson = JsonConvert.SerializeObject(output);
        return outputJson;
      }
      catch (Exception ex)
      {
        throw new Exception($"Failed to convert feed: {ex.Message}", ex);
      }
    }
  }
}

So the code will read the XML string into a XDocument object. Then iterate over all of the “product” items in the XML document. The dynamic class in C# is a static type where type-checking is disabled, so we can create our own properties for that class. This is done using the ExpandoObject class.

Finally NewtonSoft.JSON is capable of serializing dynamic types into JSON, so the methods ends with taking the output array and serializing it.

That’s it. You are now a XML and JSON conversion expert. Happy coding.

MORE TO READ:


Viewing all articles
Browse latest Browse all 276

Trending Articles