Mohanapriya R Mohanapriya R
Updated date Jun 12, 2024
In this article, we will learn how to convert XML data to JSON format using C#.
  • 1.5k
  • 0
  • 0

XML and JSON:

XML, or Extensible Markup Language, is a hierarchical data format that uses tags to structure data. It is highly versatile and has been a standard for data exchange for many years. However, XML can be verbose and complex, making it less suitable for modern web applications.

JSON, or JavaScript Object Notation, is a lightweight data-interchange format inspired by JavaScript object literal syntax. It's concise, easy to read, and widely supported by modern programming languages. JSON is preferred for web APIs and data transmission between client and server.

Converting XML to JSON in C#:

In C#, we can use the System.Xml.Linq namespace to parse XML data and the Newtonsoft.Json library to work with JSON. 

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

class Program
{
    static void Main()
    {
        string xmlString = "<book><title>Beauty World</title><author>Priya R</author></book>";
        XDocument xmlDoc = XDocument.Parse(xmlString);

        JObject jsonObj = new JObject(
            xmlDoc.Root.Elements()
            .Select(el => new JProperty(el.Name.LocalName, el.Value)));

        Console.WriteLine(jsonObj.ToString());
    }
}

Output:

{
  "title": "Beauty World",
  "author": "Priya R"
}

Comments (0)

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