How to convert JSON to XML and XML to JSON



we will be using the Console Application example, but you can use the same C# code in ASP.NET MVC or Web-Form or even in .NET Core.

You can convert XML to JSON 

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

namespace Csharp_Code_XMLtoJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            var xml = @"<person xmlns:json='https://csharpcode.in/projects/json' id='1'>
						  <name>Csharp</name>
						  <url>https://csharpcode.in/</url>
						  <role json:Array='true'>Project Manager</role>
						</person>";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            string jsonText = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);
            Console.WriteLine(jsonText);
        }
    }
}

You can convert JSON to XML

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

namespace Csharp_Code_JSONToXML
{
    class Program
    {        
        static void Main(string[] args)
        {
			string json = @"{
				  '?xml': {
					'@version': '1.0',
					'@standalone': 'no'
				  },
				  'books': {
					'book': [
					  {
						'@id': 'bk101',
						'author': 'Csharp Code-0',
						'title': 'XML Developer\'s Guide',
						'price': '44.95',
					  },
					  {
						'@id': 'bk102',
						'author': 'Csharp, Code-1',
						'title': 'Midnight Rain',
						'price': '5.95',
					  }
					]
				  }
				}";
            XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
			Console.WriteLine(doc.OuterXml);
        }
    }
}

0 Comment's

Comment Form

Submit Comment