原文:ASP.NET中XML转JSON的方法

许多应用程序都将数据存储为XML的格式,而且会将数据以JSON的格式发送到客户端以做进一步处理。要实现这一点,它们必须将XML格式转换为JSON格式。

XML转JSON代码

  1. private static string XmlToJSON(XmlDocument xmlDoc)
  2. {
  3. StringBuilder sbJSON = new StringBuilder();
  4. sbJSON.Append("{ ");
  5. XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
  6. sbJSON.Append("}");
  7. return sbJSON.ToString();
  8. }
  9. //  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array
  10. private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
  11. {
  12. if (showNodeName)
  13. sbJSON.Append("\\"" + SafeJSON(node.Name) + "\\": ");
  14. sbJSON.Append("{");
  15. // Build a sorted list of key-value pairs
  16. //  where   key is case-sensitive nodeName
  17. //          value is an ArrayList of string or XmlElement
  18. //  so that we know whether the nodeName is an array or not.
  19. SortedList childNodeNames = new SortedList();
  20. //  Add in all node attributes
  21. if( node.Attributes!=null)
  22. foreach (XmlAttribute attr in node.Attributes)
  23. StoreChildNode(childNodeNames,attr.Name,attr.InnerText);
  24. //  Add in all nodes
  25. foreach (XmlNode cnode in node.ChildNodes)
  26. {
  27. if (cnode is XmlText)
  28. StoreChildNode(childNodeNames, "value", cnode.InnerText);
  29. else if (cnode is XmlElement)
  30. StoreChildNode(childNodeNames, cnode.Name, cnode);
  31. }
  32. // Now output all stored info
  33. foreach (string childname in childNodeNames.Keys)
  34. {
  35. ArrayList alChild = (ArrayList)childNodeNames[childname];
  36. if (alChild.Count == 1)
  37. OutputNode(childname, alChild[0], sbJSON, true);
  38. else
  39. {
  40. sbJSON.Append(" \\"" + SafeJSON(childname) + "\\": [ ");
  41. foreach (object Child in alChild)
  42. OutputNode(childname, Child, sbJSON, false);
  43. sbJSON.Remove(sbJSON.Length - 2, 2);
  44. sbJSON.Append(" ], ");
  45. }
  46. }
  47. sbJSON.Remove(sbJSON.Length - 2, 2);
  48. sbJSON.Append(" }");
  49. }
  50. //  StoreChildNode: Store data associated with each nodeName
  51. //                  so that we know whether the nodeName is an array or not.
  52. private static void StoreChildNode(SortedList childNodeNames, string nodeName, object nodeValue)
  53. {
  54. // Pre-process contraction of XmlElement-s
  55. if (nodeValue is XmlElement)
  56. {
  57. // Convert  <aa></aa> into "aa":null
  58. //          <aa>xx</aa> into "aa":"xx"
  59. XmlNode cnode = (XmlNode)nodeValue;
  60. if( cnode.Attributes.Count == 0)
  61. {
  62. XmlNodeList children = cnode.ChildNodes;
  63. if( children.Count==0)
  64. nodeValue = null;
  65. else if (children.Count == 1 && (children[0] is XmlText))
  66. nodeValue = ((XmlText)(children[0])).InnerText;
  67. }
  68. }
  69. // Add nodeValue to ArrayList associated with each nodeName
  70. // If nodeName doesn't exist then add it
  71. object oValuesAL = childNodeNames[nodeName];
  72. ArrayList ValuesAL;
  73. if (oValuesAL == null)
  74. {
  75. ValuesAL = new ArrayList();
  76. childNodeNames[nodeName] = ValuesAL;
  77. }
  78. else
  79. ValuesAL = (ArrayList)oValuesAL;
  80. ValuesAL.Add(nodeValue);
  81. }
  82. private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
  83. {
  84. if (alChild == null)
  85. {
  86. if (showNodeName)
  87. sbJSON.Append("\\"" + SafeJSON(childname) + "\\": ");
  88. sbJSON.Append("null");
  89. }
  90. else if (alChild is string)
  91. {
  92. if (showNodeName)
  93. sbJSON.Append("\\"" + SafeJSON(childname) + "\\": ");
  94. string sChild = (string)alChild;
  95. sChild = sChild.Trim();
  96. sbJSON.Append("\\"" + SafeJSON(sChild) + "\\"");
  97. }
  98. else
  99. XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
  100. sbJSON.Append(", ");
  101. }
  102. // Make a string safe for JSON
  103. private static string SafeJSON(string sIn)
  104. {
  105. StringBuilder sbOut = new StringBuilder(sIn.Length);
  106. foreach (char ch in sIn)
  107. {
  108. if (Char.IsControl(ch) || ch == '\\'')
  109. {
  110. int ich = (int)ch;
  111. sbOut.Append(@"\\u" + ich.ToString("x4"));
  112. continue;
  113. }
  114. else if (ch == '\\"' || ch == '\\\\' || ch == '/')
  115. {
  116. sbOut.Append('\\\\');
  117. }
  118. sbOut.Append(ch);
  119. }
  120. return sbOut.ToString();
  121. }

ASP.NET中XML转JSON的方法的更多相关文章

  1. ASP.net中导出Excel的简单方法介绍

    下面介绍一种ASP.net中导出Excel的简单方法 先上代码:前台代码如下(这是自己项目里面写的一点代码先贴出来吧) <div id="export" runat=&quo ...

  2. xml转json的方法

    .第一种方法 使用JSON-JAVA提供的方法,之前一直使用json-lib提供的方法转json,后来发现了这个开源项目,觉得用起来很不错,并且可以修改XML.java中的parse方法满足自己的转换 ...

  3. C#中XML和json互相转换

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xm ...

  4. asp.net中获取当前url的方法

    HttpContext.Current.Request.Url.ToString() 并不可靠. 如果当前URL为 http://localhost/search.aspx?user=http://c ...

  5. 在Asp.Net中使用SmtpMail发送邮件的方法

    在ASP中,就可以通过调用CDONTS组件发送简单邮件,在ASP.Net中,自然也可以.不同的是,.Net Framework中,将这一组件封装到了System.Web.Mail命名空间中. 一个典型 ...

  6. 慎重Asp.net中static变量的使用方法

    在.Net平台下进行CS软件开发时,我们常常遇到以后还要用到某些变量上次改动后的值,为了简单起见,非常多人都习惯用static来定义这些变量,我也是.这样非常方便.下一次调用某个函数时该变量仍然保存的 ...

  7. java中常见的json解析方法、库以及性能对比

    常见的json解析有原生的JSONObject和JSONArray方法,谷歌的GSON库,阿里的fastjson,还有jackson,json-lib. Gson(项目地址:https://githu ...

  8. java 中xml转换为json对象

    1.前提须要jar包: json-lib-2.4-jdk15.jar 和 xom-1.2.5.jar ,maven 仓库: net.sf.json-lib json-lib 2.4 jdk15 xom ...

  9. java中Xml、json之间的相互转换

    旁白: 最近关于xml与json之间的转换都搞蒙了,这里写一个demo,以后备用. 正题: project格式是: jar包是一个一个检出来的,还算干净了. 代码: 工具类: package exer ...

随机推荐

  1. Entity Framework笔记(二)

    前几日学习了在VS2010Console项目中使用Entity Framework,并且使用Code First模式.通过编写Model类,来生成数据库对应的表.并且,往表中写入数据以及获取表中的所有 ...

  2. 【SSH 基金会】SSH框架--struts进一步的详细解释(两)

    继上篇博客 既然我们知道了不使用struts给我们带来这么多弊端,那么以下我们来看看struts是怎样封装的.怎么解决我们出现的问题的? 先来说一下struts的基本流程,帮助大家理解以下的代码: S ...

  3. 补间动画实现(tween)

    1.补间动画的概念: 补间动画:仅仅须要开发人员设置好动画的開始与结束的关键帧 中间帧有喜用计算机补齐. 2.种类:分为4种: ①alpha 透明度 ②alpha 透明度 ③translate 位置移 ...

  4. java多线程学习(一)

    一.操作系统线程和进程的概念 线程是指进程中的一个运行单元,这个过程中也可调度实体. 线程与进程的差别: (1)地址空间:线程为进程内的一个运行单元.进程至少有一个线程(进程的主线程):进程的全部线程 ...

  5. 如何有效地记录 Java SQL 日志(转)

    在常规项目的开发中可能最容易出问题的地方就在于对数据库的处理了,在大部分的环境下,我们对数据库的操作都是使用流行的框架,比如 Hibernate . MyBatis 等.由于各种原因,我们有时会想知道 ...

  6. Angular报错记录

    一 找不到Controller 出现这种错误,一般都是没有找到需要的Controller,需要仔细检查是否所需的Controller已经正确引入

  7. dp related problems (update continuously)

    Leetcode Maximum Product Subarray 这个问题是说给一个整数数组.求最大连续子阵列产品. 纠结了包括阵列中的很长一段时间0而如何处理负数,关键的事实是,负治疗,所以我们录 ...

  8. Javascript学习7 - 脚本化浏览器窗口

    原文:Javascript学习7 - 脚本化浏览器窗口 本节讨论了文档对象模型.客户端Javascript下Window中的各项属性,包括计时器.Location对象.Histroy对象.窗口.浏览器 ...

  9. 《python源代码分析》笔记 pythonVM一般表达式

    本文senlie原版的.转载请保留此地址:http://blog.csdn.net/zhengsenlie 1.字节码指令 LOAD_CONST:从consts表中读取序号为i的元素并压入到执行时栈中 ...

  10. JS动态获取浏览器宽度和高度

    $(window).resize(function() { var width = $(this).width(); var height = $(this).height(); });