[技術] JSON和XML的轉換 (Convert between JSON and XML)

[技術] JSON和XML的轉換

首先,將NewtonSoft.Json加入參考

再using Newtonsoft.Json;

接下來便可使用以下程式碼。

1. 將XML轉換成JSON格式

   1: string xml = @"<?xml version=""1.0"" standalone=""no""?>
   2: <root>
   3:   <person id=""1"">
   4:   <name>Alan</name>
   5:   <url>http://www.google.com</url>
   6:   </person>
   7:   <person id=""2"">
   8:   <name>Louis</name>
   9:   <url>http://www.yahoo.com</url>
  10:   </person>
  11: </root>";
  12:  
  13: XmlDocument doc = new XmlDocument();
  14: doc.LoadXml(xml);
  15:  
  16: string jsonText = JsonConvert.SerializeXmlNode(doc);
  17: //{
  18: //  "?xml": {
  19: //    "@version": "1.0",
  20: //    "@standalone": "no"
  21: //  },
  22: //  "root": {
  23: //    "person": [
  24: //      {
  25: //        "@id": "1",
  26: //        "name": "Alan",
  27: //        "url": "http://www.google.com"
  28: //      },
  29: //      {
  30: //        "@id": "2",
  31: //        "name": "Louis",
  32: //        "url": "http://www.yahoo.com"
  33: //      }
  34: //    ]
  35: //  }
  36: //}

 

 

2. 將JSON轉換成XML格式

   1: string json = @"{
   2:   ""?xml"": {
   3:     ""@version"": ""1.0"",
   4:     ""@standalone"": ""no""
   5:   },
   6:   ""root"": {
   7:     ""person"": [
   8:       {
   9:         ""@id"": ""1"",
  10:         ""name"": ""Alan"",
  11:         ""url"": ""http://www.google.com""
  12:       },
  13:       {
  14:         ""@id"": ""2"",
  15:         ""name"": ""Louis"",
  16:         ""url"": ""http://www.yahoo.com""
  17:       }
  18:     ]
  19:   }
  20: }";
  21:  
  22: XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
  23: // <?xml version="1.0" standalone="no"?>
  24: // <root>
  25: //   <person id="1">
  26: //   <name>Alan</name>
  27: //   <url>http://www.google.com</url>
  28: //   </person>
  29: //   <person id="2">
  30: //   <name>Louis</name>
  31: //   <url>http://www.yahoo.com</url>
  32: //   </person>
  33: // </root>