Json.Net学习笔记(三) Json与Xml之间的转换

Json.Net 支持 Json 与Xml之间的相互转换.

转换规则:

 1.元素保持不变
 2.属性添加前缀@
 3.单个子文本结点直接作为元素结点的值,否则通过#text访问
 4.XML声明和处理指令以?为前缀
 5.字符数据(Character data)、注释、whitespace 和significate whitespace结点分别通过#cdata-section,#comment,#whitespace and #significate-whitespace 访问。
 6.同一级多个相同名字的结点作为一组,放到同一个集合中
 7.空元素为null

using Newtonsoft.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>
                            Hello World
                            </root>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

           //XML to JSON
            string jsonText = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);
            Console.WriteLine(jsonText);

输出结果:

{
  "?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"
      }
    ],
    "#text": "\r\n                            Hello World\r\n                            "
  }
}

 

            //JSON to XML

            XmlDocument docJson = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonText);
            Console.WriteLine(docJson.InnerXml);

posted @ 2011-06-11 15:04  资源收集  阅读(1024)  评论(0编辑  收藏  举报