How to Converting JSON to XML in C#?
JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are two commonly used formats for representing and transmitting data. While both have their strengths and use cases, there are times when you may need to convert data from JSON to XML or vice versa. In this article, we will focus on the process of converting JSON data to XML using C#.
This C# program takes JSON data as input and produces XML output. Below is the C# code for the program:
using System;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
static void Main()
{
// JSON input string
string jsonString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
// Convert JSON to JObject
JObject json = JObject.Parse(jsonString);
// Create XML document
XmlDocument xmlDocument = new XmlDocument();
// Add root element
XmlElement rootElement = xmlDocument.CreateElement("Person");
xmlDocument.AppendChild(rootElement);
// Convert JSON properties to XML elements
foreach (var property in json.Properties())
{
XmlElement element = xmlDocument.CreateElement(property.Name);
element.InnerText = property.Value.ToString();
rootElement.AppendChild(element);
}
// Display XML
Console.WriteLine(xmlDocument.OuterXml);
}
}
In this program, we start with a JSON string representing a person's information. We then use the Newtonsoft.Json
library to parse the JSON string into a JObject
. Next, we create an XmlDocument
to hold the XML data. We iterate through the properties of the JObject
, creating XML elements for each property and appending them to the root element. Finally, we display the resulting XML.
When we run this program, the output will be the equivalent XML representation of the input JSON data:
<Person>
<name>John</name>
<age>30</age>
<city>New York</city>
</Person>
As you can see, the JSON data has been successfully converted to XML format.
Comments (0)