154-convert-xml-to-json-in-c

If XML data are small in structure, there is a way to convert XML to json in C# by knowing how to serialize dictionary to json in C#. We need to use

using System.Web.Script.Serialization;

namespace. It has to be added as reference to our project, by including System.Web.Extensions.dll into our project. Funny thing is that this dll file is in your dot. net framework, but for some reason C# might not see it. That’s why it has to be added to project as reference manually. We also need to use

using System.Xml.Linq;
using System.Linq;

Then, we can form our XML data structure by using LINQ i.e. Xml.LINQ:

var xml =
@”<Columns>
<Column Name=””car1″” DataType=””String””>Fiat</Column>
<Column Name=””car2″” DataType=””String””>Mercedes</Column>
<Column Name=””car3″” DataType=””String””>Renault</Column>
</Columns>”;
var dic = XDocument

.Parse(xml)
.Descendants(“Column”)
.ToDictionary(

c => c.Attribute(“Name”).Value,
c => c.Value

);

Once when we have our XML data converted into dictionary, it is easy to serialize dictionary to json:

var json = new JavaScriptSerializer().Serialize(dic);
string str_out = json.ToString();
textBox1.Text = str_out;

However, this is not so practical method for real life XML. Since dictionary is key – value pair data structure, for normal XML where there is a deep hierarchy among nodes and a lot of column like attributes per node. It is much easier to serialize XML to json in C# by using Newtonsoft.Json framework. Installation of Newtonsoft.Json framework has to be done by using nuget. For that purpose we need to have complete visual studio for desktop installed on our PC. Go to Tools → Extensions and Updates…

nuget01

And then, go to Online → Visual Studio Gallery → NuGet Package Manager and click to Download.

nuget02

After this procedure is done, our job is easy, since Newtonsoft.Json framework will do the job for us. Now we only need to use

using Newtonsoft.Json;
using System.Xml;

namespaces. Next few lines of the code will do the job.

string str_xmlFile;
if( openFileDialog1.ShowDialog()== DialogResult.OK )
{

str_xmlFile = openFileDialog1.FileName;

this.Text = str_xmlFile;

XmlDocument doc = new XmlDocument();

doc.Load(str_xmlFile);

string jsonText = JsonConvert.SerializeXmlNode(doc);

textBox1.Text = jsonText;

}

There is only one thing left to care about. Load XML document with Load() method, not LoadXml(). If we make mistake and use LoadXml following error occurs:

Load-xml

So, be careful and use Load() method to load XML from file!

Read how to send your Json data to wbsite over http protocol
Read about HtmlAgilityPack
Read how to convert Json to XML.

External links:

XML to Json conversion in C# on Stackoverflow

XML to Json conversion in C# on NewtonSoft

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*