Created
July 29, 2012 08:52
-
-
Save aturgarg/3196810 to your computer and use it in GitHub Desktop.
Json to xml and vice-versa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Xml; | |
/* | |
* download NewtonSoft josn library from | |
* http://www.codeplex.com/json/Release/ProjectReleases.aspx | |
* */ | |
using Newtonsoft.Json; | |
using System.IO; | |
using System.Xml.Linq; | |
namespace xmlsoap | |
{ | |
class xmlsoap | |
{ | |
static void Main(string[] args) | |
{ | |
xmlsoap obj = new xmlsoap(); | |
obj.Test(); | |
Console.ReadLine(); | |
} | |
public void Test() | |
{ | |
string xml = @"<?xml version=""1.0"" standalone=""no""?> | |
<root> | |
<person id=""1""> | |
<name>Alan</name> | |
<url>http://www.google.com</url> | |
</person> | |
<person id=""2""> | |
<name>Louis</name> | |
<url>http://www.yahoo.com</url> | |
</person> | |
</root>"; | |
XmlDocument doc = new XmlDocument(); | |
doc.LoadXml(xml); | |
string jsonText = JsonConvert.SerializeXmlNode(doc); | |
Console.WriteLine("\nxml to json : "); | |
Console.WriteLine(jsonText); | |
string json = @"{ | |
""?xml"": { | |
""@version"": ""1.0"", | |
""@standalone"": ""no"" | |
}, | |
""root"": { | |
""person"": [ | |
{ | |
""@id"": ""1"", | |
""name"": ""Alan"", | |
""url"": ""http://www.google.com"" | |
}, | |
{ | |
""@id"": ""2"", | |
""name"": ""Louis"", | |
""url"": ""http://www.yahoo.com"" | |
} | |
] | |
} | |
}"; | |
XmlDocument xmldoc = (XmlDocument)JsonConvert.DeserializeXmlNode(json); | |
//convert xml to string | |
string xmlStr = ConvertXmlDocumentToString(xmldoc); | |
Console.WriteLine("\njson to xml : "); | |
Console.WriteLine(xmlStr); | |
} | |
private string ConvertXmlDocumentToString(XmlDocument xmldoc) | |
{ | |
StringWriter sw = new StringWriter(); | |
XmlTextWriter tx = new XmlTextWriter(sw); | |
xmldoc.WriteTo(tx); | |
return sw.ToString(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment