详细介绍XML与JSON相互转换(图文)

JOSN简介

在本系列的第一篇已经简单比较了xml和json 时光机

JSON:JavaScript 对象表示法(JavaScript Object Notation)。 JSON 是存储和交换文本信息的语法。类似 XML。 JSON 比 XML 更小、更快,更易解析。

什么是 JSON?

JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻量级的文本数据交换格式 JSON 独立于语言 * JSON 具有自我描述性,更易理解

JSON 使用 JavaScript 语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。

JSON格式化

尽管有许多宣传关于 XML 如何拥有跨平台,跨语言的优势,然而,除非应用于 Web Services,否则,在普通的 Web 应用中,开发者经常为 XML 的解析伤透了脑筋,无论是服务器端生成或处理 XML,还是客户端用 JavaScript 解析 XML,都常常导致复杂的代码,极低的开发效率。实际上,对于大多数 Web 应用来说,他们根本不需要复杂的 XML 来传输数据,XML 的扩展性很少具有优势,许多 AJAX 应用甚至直接返回 HTML 片段来构建动态 Web 页面。和返回 XML 并解析它相比,返回 HTML 片段大大降低了系统的复杂性,但同时缺少了一定的灵活性

XML2JOSN

借助第三方类库转换 

1256.png

使用NuGet添加第三方类库

1255.png

string xml = @"Alanhttp://www.google.comLouishttp://www.yahoo.com"; 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"//      }//    ]//  }//}

登录后复制

1257.png

对于每个表标签的属性对应JSON中的”@”标签名
如果有多个同名标签就会添加到一个数组集合中

其他方式转换

1.使用.NET Framework中的JavaScriptSerializer类

首先需要确保你的工程或服务器支持.NET 4.0或以上版本的Framework,否则无法找到该类。
通过JavaScriptSerializer来实现。它的名字空间为:System.Web.Script.Serialization
如果要使用它,还须添加
System.Web.Extensions库文件引用

  var xml =                   @"          True          Hello World          999        ";            var dic = XDocument                .Parse(xml)                .Descendants("Column")                .ToDictionary(                    c => c.Attribute("Name").Value,                    c => c.Value                );            var json = new JavaScriptSerializer().Serialize(dic);            Console.WriteLine(json);

登录后复制

1258.png

2.手动编写转换类

  public class Xml2JSON    {        public static string XmlToJSON(XmlDocument xmlDoc)        {            StringBuilder sbJSON = new StringBuilder();            sbJSON.Append("{ ");            XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);            sbJSON.Append("}");            return sbJSON.ToString();        }         //  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array        private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)        {            if (showNodeName)                sbJSON.Append(""" + SafeJSON(node.Name) + "": ");            sbJSON.Append("{");            // Build a sorted list of key-value pairs            //  where   key is case-sensitive nodeName            //          value is an ArrayList of string or XmlElement            //  so that we know whether the nodeName is an array or not.            SortedList childNodeNames = new SortedList();             //  Add in all node attributes            if (node.Attributes != null)                foreach (XmlAttribute attr in node.Attributes)                    StoreChildNode(childNodeNames, attr.Name, attr.InnerText);             //  Add in all nodes            foreach (XmlNode cnode in node.ChildNodes)            {                if (cnode is XmlText)                    StoreChildNode(childNodeNames, "value", cnode.InnerText);                else if (cnode is XmlElement)                    StoreChildNode(childNodeNames, cnode.Name, cnode);            }             // Now output all stored info            foreach (string childname in childNodeNames.Keys)            {                ArrayList alChild = (ArrayList)childNodeNames[childname];                if (alChild.Count == 1)                    OutputNode(childname, alChild[0], sbJSON, true);                else                {                    sbJSON.Append(" "" + SafeJSON(childname) + "": [ ");                    foreach (object Child in alChild)                        OutputNode(childname, Child, sbJSON, false);                    sbJSON.Remove(sbJSON.Length - 2, 2);                    sbJSON.Append(" ], ");                }            }            sbJSON.Remove(sbJSON.Length - 2, 2);            sbJSON.Append(" }");        }         //  StoreChildNode: Store data associated with each nodeName        //                  so that we know whether the nodeName is an array or not.        private static void StoreChildNode(SortedList childNodeNames, string nodeName, object nodeValue)        {            // Pre-process contraction of XmlElement-s            if (nodeValue is XmlElement)            {                // Convert   into "aa":null                //          xx into "aa":"xx"                XmlNode cnode = (XmlNode)nodeValue;                if (cnode.Attributes.Count == 0)                {                    XmlNodeList children = cnode.ChildNodes;                    if (children.Count == 0)                        nodeValue = null;                    else if (children.Count == 1 && (children[0] is XmlText))                        nodeValue = ((XmlText)(children[0])).InnerText;                }            }            // Add nodeValue to ArrayList associated with each nodeName            // If nodeName doesn't exist then add it            object oValuesAL = childNodeNames[nodeName];            ArrayList ValuesAL;            if (oValuesAL == null)            {                ValuesAL = new ArrayList();                childNodeNames[nodeName] = ValuesAL;            }            else                ValuesAL = (ArrayList)oValuesAL;            ValuesAL.Add(nodeValue);        }         private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)        {            if (alChild == null)            {                if (showNodeName)                    sbJSON.Append(""" + SafeJSON(childname) + "": ");                sbJSON.Append("null");            }            else if (alChild is string)            {                if (showNodeName)                    sbJSON.Append(""" + SafeJSON(childname) + "": ");                string sChild = (string)alChild;                sChild = sChild.Trim();                sbJSON.Append(""" + SafeJSON(sChild) + """);            }            else                XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);            sbJSON.Append(", ");        }         // Make a string safe for JSON        private static string SafeJSON(string sIn)        {            StringBuilder sbOut = new StringBuilder(sIn.Length);            foreach (char ch in sIn)            {                if (Char.IsControl(ch) || ch == ''')                {                    int ich = (int)ch;                    sbOut.Append(@"u" + ich.ToString("x4"));                    continue;                }                else if (ch == '"' || ch == '\' || ch == '/')                {                    sbOut.Append('\');                }                sbOut.Append(ch);            }            return sbOut.ToString();        }    }

登录后复制

1259.png

JOSN2XML

借助第三方类库转换

1260.png

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 = JsonConvert.DeserializeXmlNode(json);doc.Save(@"D:json.xml");// // //   //     Alan//     http://www.google.com//   //   //     Louis//     http://www.yahoo.com//   // 

登录后复制

其他方式转换

1261.png

以上就是详细介绍XML与JSON相互转换(图文)的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2418868.html

(0)
上一篇 2025年3月3日 02:29:35
下一篇 2025年2月20日 00:04:09

AD推荐 黄金广告位招租... 更多推荐

发表回复

登录后才能评论