How to Convert JSON to XML Using C#

Jan 28, 2024

2 mins read

Published in

Converting JSON to XML in C#: A Step-by-Step Guide

In modern software development, data interchange between systems is a common task. JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are two widely used formats for data representation. In this tutorial, we’ll explore how to convert JSON to XML using C#.

Prerequisites:

  • Basic understanding of C#
  • Visual Studio installed on your system

Step 1: Setting Up Your Project

Start by opening Visual Studio and creating a new C# console application project. Name it “JSONtoXMLConverter”.

Step 2: Adding Newtonsoft.Json Package

We’ll use the Newtonsoft.Json library for JSON manipulation. To add it to your project, right-click on your project in Solution Explorer, select “Manage NuGet Packages,” search for “Newtonsoft.Json,” and install it.

Step 3: Writing the Conversion Code

Now, let’s write the code to convert JSON to XML. Create a new class file named “Converter.cs” and add the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Xml.Linq;

namespace JSONtoXMLConverter
{
    public static class Converter
    {
        public static string ConvertJsonToXml(string jsonString)
        {
            JObject jsonObject = JObject.Parse(jsonString);
            XNode convertedXml = JsonConvert.DeserializeXNode(jsonObject.ToString(), "Root");
            return convertedXml.ToString();
        }
    }
}

This code defines a static method ConvertJsonToXml that takes a JSON string as input and returns the corresponding XML string.

Step 4: Implementing the Main Method

Now, let’s implement the main method to test our conversion. Open the “Program.cs” file and replace its content with the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
using System;

namespace JSONtoXMLConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
            string xmlString = Converter.ConvertJsonToXml(jsonString);
            Console.WriteLine("Converted XML:");
            Console.WriteLine(xmlString);
        }
    }
}

This code creates a sample JSON string, converts it to XML using our Converter class, and then prints the resulting XML to the console.

Step 5: Running the Application

Build and run the application. You should see the JSON string converted to XML format in the console output.

In this tutorial, we’ve learned how to convert JSON to XML using C# with the help of the Newtonsoft.Json library. Understanding data interchange formats like JSON and XML and knowing how to manipulate them programmatically is essential for modern software development. Feel free to explore further and adapt this code to your specific requirements.

Sharing is caring!