Tuesday, 12 May 2015

How to convert JSON String into XML Document in c# .NET?

Here I expalined JSON and XML in briefly because this post  is how to convert JSON into XMl Doc

Whta is JSON:-

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.

Example :-

       var jason = {
                     "age" : "24",
                     "hometown" : "Missoula, MT",
                     "gender" : "male"

                   };

What si XML :-
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format which is both human-readable and machine-readable.

Example:-

<?xml version="1.0" encoding="UTF-8" ?>
<Emp Id>rps101</Emp Id>
<EmpName>Rampal</EmpName>
<EmpDOB>12-05-2015</EmpDOB>
<Salary>50000</Salary>
<Designation>Developer</Designation>


Now here I worte how to convert JSON string into XMl Document.

Source code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
using Newtonsoft.Json;

namespace ConsoleAppDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // sample json string
            String Json = "{\"Name\": \"Rampal\", \"Gender\": \"Male\",
            \"EmailId\": \"rphbti640@gmail.com\", \"MobileNo\": \"8861447949\", 
            \"City\": \"Bangluru\", \"Country\": \"India\"}";

            // Pass the json string to below method
            string smlDoc = ConvertJsonToXMLDoc(Json);
            Console.WriteLine(smlDoc);
            Console.ReadKey();

           
        }


        public static string ConvertJsonToXMLDoc(string jsondata)
        {
            string ResponseXMLData = string.Empty;
            // use the method DeserializeXmlNode abailabe in Newtonsoft.Json namespace
            XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsondata, "DocumentElement");
            // Create an instance of string writer class
            StringWriter sw = new StringWriter();
            // Create an instance of XML writer class
            XmlTextWriter xw = new XmlTextWriter(sw);
            // set the indented formate
            xw.Formatting = System.Xml.Formatting.Indented;
            // write as XML Doc
            doc.WriteTo(xw);
            return sw.ToString();
        }
    }

}

Output:-

No comments:

Post a Comment