In previous article we discussed how to convert XML data to json format. Converting in opposite direction is as just as simple. So to convert json to XML in C# let’s assume that we have data in json format are stored in text file. We need to open this file first.
string str_file_to_open;
str_file_to_open = openFileDialog2.FileName;
string str_tex_to_read;
StreamReader sr_StreamReader = new StreamReader(str_file_to_open);
str_tex_to_read = sr_StreamReader.ReadToEnd();
sr_StreamReader.Close();
When data are stored into string, we can de-serialize them in one line of code
XmlDocument doc = JsonConvert.DeserializeXmlNode(str_tex_to_read);
if, of course we have Newtonsoft.Json framework already installed and namespace
using Newtonsoft.Json;
included. Having data in XML format, we might want to convert XML document to text in C#. For that purpose, we can use StringWriter object and it’s GetStringBuilder() method.
string str_xml_to_text;
using (var stringWriter = new StringWriter())
{
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
doc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
str_xml_to_text = stringWriter.GetStringBuilder().ToString();
}
}
Whole code is:
if( openFileDialog2.ShowDialog() == DialogResult.OK)
{
string str_file_to_open;
str_file_to_open = openFileDialog2.FileName;
string str_tex_to_read;
StreamReader sr_StreamReader = new StreamReader(str_file_to_open);
str_tex_to_read = sr_StreamReader.ReadToEnd();
sr_StreamReader.Close();
XmlDocument doc = JsonConvert.DeserializeXmlNode(str_tex_to_read);
string str_xml_to_text;
using (var stringWriter = new StringWriter())
{
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
doc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
str_xml_to_text = stringWriter.GetStringBuilder().ToString();
}
}
textBox1.Text = str_xml_to_text;
}
Read how to convert XML to json.
External links:
Convert XML Document to Text on C# on Stackoverflow
Convert Json to XML in C# on Stackoverflow
Convert Json to XML in C# on Microsoft
Leave a Reply