Using JSON. NET in C to realize mutual conversion between JSON and XML

  • 2021-08-28 20:49:48
  • OfStack

Official JSON. NET address
http://james.newtonking.com/pages/json-net.aspx

XML TO JSON


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);
//{
// "?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"
//   }
//  ]
// }
//}

JSON TO XML


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 doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
// <?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>

DEMO:JSON TO XML


string json_str = "{\"a\":\"a\",\"b\":\"b\"}";
//json  The string of needs to follow this format   Write, or you will report an error 
string json = @"{
 ""?xml"": {
  ""@version"": ""1.0"",
  ""@standalone"": ""no""
 },
 ""root"":" + json_str + "}";
 
if (!string.IsNullOrEmpty(json))
{
  XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
   
}


Related articles: