c# XML解析成EasyUI TreeGrid格式

1.分析EasyUI TreeGrid的数据格式,demo的格式是这样的:http://www.jeasyui.net/demo/treegrid_data1.json

分析之后,得到基本的JSON格式:

[
    {
        "id": 1,
        "name": "name1",
        "value": "",
        "children": [
            {
                "id": 2,
                "name": "name2",
                "value": "value2"
            },
            {
                "id": 3,
                "name": "name3",
                "value": "",
                "children": [
                    {
                        "id": 111,
                        "name": "name4",
                        "value": "value4"
                    }
                ]
            }
        ]
    }
]

2.XML解析成JSON格式

截取其中一小部分XML的格式:

<?xml version="1.0" encoding="gb2312"?>
<Metadata>
    <mdTitle>安庆幅</mdTitle>
    <mdDataSt>2006-01-04</mdDataSt>
    <mdChar>029</mdChar>
    <mdStanName>地质信息元数据标准</mdStanName>
    <mdStanVer>2005版</mdStanVer>
    <mdLang>中文</mdLang>
    <dataIdInfo>
        <dataChar>029</dataChar>
        <idAbs> 1:20万自然重砂数据库。</idAbs>
        <idPurp>所提供得的空间位置适用。</idPurp>
        <idStatus>001</idStatus>
        <imageID></imageID>
        <dataLangCode>中文</dataLangCode>
    </dataIdInfo>
</Metadata>

找到这篇博文,于是拿过来用了,在此基础上做了修改,改成TreeGrid的json格式。博文链接:http://www.cnblogs.com/jaxu/p/3296148.html,博主写的很好呢!

用的一般处理程序,直接将源码贴出来。。。

  1    /// <summary>
  2     /// XmlToJson 的摘要说明
  3     /// </summary>
  4     public class XmlToJson : IHttpHandler
  5     {
  6         public int id = 0;
  7         public void ProcessRequest(HttpContext context)
  8         {
  9             context.Response.ContentType = "text/plain";
 10             //String filename = context.Request.Params["fileaddr"];
 11             String strResponse = "";
 12
 13             XmlDocument doc = new XmlDocument();
 14             try
 15             {
 16                 String filepath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "data/(ah)安庆幅.xml";
 17                 doc.Load(filepath);
 18             }
 19             catch (Exception ex)
 20             {
 21
 22                 return;
 23             }
 24
 25             // Convert XML to a JSON string
 26             string JSON = XmlToJSON(doc);
 27
 28             // Replace \ with \\ because string is being decoded twice
 29             strResponse = JSON.Replace(@"\", @"\\");
 30
 31             context.Response.Write(strResponse);
 32
 33
 34         }
 35
 36         private string XmlToJSON(XmlDocument xmlDoc)
 37         {
 38             StringBuilder sbJSON = new StringBuilder();
 39             //sbJSON.Append("{");
 40             sbJSON.Append("[");
 41             XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
 42             //sbJSON.Append("}");
 43             sbJSON.Append("]");
 44             return sbJSON.ToString();
 45         }
 46
 47         //  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array
 48         private void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
 49         {
 50             if (showNodeName)
 51             {
 52                 //sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
 53                 sbJSON.Append("{\"id\":" + id + ",\"name\":\"" + TranslateName(SafeJSON(node.Name)) + "\",\"value\":\"" + "" + "\",\"children\":[");
 54                 id++;
 55             }
 56             //sbJSON.Append("{");
 57
 58             // Build a sorted list of key-value pairs
 59             //  where   key is case-sensitive nodeName
 60             //          value is an ArrayList of string or XmlElement
 61             //  so that we know whether the nodeName is an array or not.
 62             SortedList childNodeNames = new SortedList();
 63
 64             //  Add in all node attributes
 65             if (node.Attributes != null)
 66             {
 67                 foreach (XmlAttribute attr in node.Attributes)
 68                 {
 69                     StoreChildNode(childNodeNames, attr.Name, attr.InnerText);
 70                 }
 71             }
 72
 73             //  Add in all nodes
 74             foreach (XmlNode cnode in node.ChildNodes)
 75             {
 76                 if (cnode is XmlText)
 77                 {
 78                     StoreChildNode(childNodeNames, "value", cnode.InnerText);
 79                 }
 80                 else if (cnode is XmlElement)
 81                 {
 82                     StoreChildNode(childNodeNames, cnode.Name, cnode);
 83                 }
 84             }
 85
 86             // Now output all stored info
 87             foreach (string childname in childNodeNames.Keys)
 88             {
 89                 ArrayList alChild = (ArrayList)childNodeNames[childname];
 90                 if (alChild.Count == 1)
 91                     OutputNode(childname, alChild[0], sbJSON, true);
 92                 else
 93                 {
 94                     //sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
 95                     sbJSON.Append("{\"id\":" + id + ",\"name\":\"" + TranslateName(SafeJSON(childname)) + "\",\"value\":\"" + "" + "\",\"children\":[");
 96                     id++;
 97                     foreach (object Child in alChild)
 98                         OutputNode(childname, Child, sbJSON, false);
 99                     sbJSON.Remove(sbJSON.Length - 2, 2);
100                     sbJSON.Append(" ], ");
101                 }
102             }
103             sbJSON.Remove(sbJSON.Length - 2, 2);
104             //sbJSON.Append(" }");
105             sbJSON.Append(" ]}");
106         }
107
108         //  StoreChildNode: Store data associated with each nodeName
109         //                  so that we know whether the nodeName is an array or not.
110         private void StoreChildNode(SortedList childNodeNames, string nodeName, object nodeValue)
111         {
112             // Pre-process contraction of XmlElement-s
113             if (nodeValue is XmlElement)
114             {
115                 // Convert  <aa></aa> into "aa":null
116                 //          <aa>xx</aa> into "aa":"xx"
117                 XmlNode cnode = (XmlNode)nodeValue;
118                 if (cnode.Attributes.Count == 0)
119                 {
120                     XmlNodeList children = cnode.ChildNodes;
121                     if (children.Count == 0)
122                         nodeValue = null;
123                     else if (children.Count == 1 && (children[0] is XmlText))
124                         nodeValue = ((XmlText)(children[0])).InnerText;
125                 }
126             }
127             // Add nodeValue to ArrayList associated with each nodeName
128             // If nodeName doesn‘t exist then add it
129             object oValuesAL = childNodeNames[nodeName];
130             ArrayList ValuesAL;
131             if (oValuesAL == null)
132             {
133                 ValuesAL = new ArrayList();
134                 childNodeNames[nodeName] = ValuesAL;
135             }
136             else
137             {
138                 //ValuesAL = (ArrayList)oValuesAL;
139          //使用的SortedList,所以名称不能相同,这里偷了个懒没有修改。。
140                 //如果同一级子节点下有相同名称的节点,那么重新命名
141                 ValuesAL = new ArrayList();
142                 childNodeNames[nodeName + id] = ValuesAL;
143             }
144
145             ValuesAL.Add(nodeValue);
146         }
147
148         private void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
149         {
150             if (alChild == null)
151             {
152                 if (showNodeName)
153                 {
154                     //sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
155                     sbJSON.Append("{\"id\":" + id + ",\"name\":\"" + TranslateName(SafeJSON(childname)) + "\",\"value\":\"\"}");
156                     id++;
157                 }
158                 //sbJSON.Append("null");
159             }
160             else if (alChild is string)
161             {
162                 if (showNodeName)
163                 {
164                     //sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
165                     sbJSON.Append("{\"id\":" + id + ",\"name\":\"" + TranslateName(SafeJSON(childname)) + "\",\"value\":");
166                     id++;
167                 }
168                 string sChild = (string)alChild;
169                 sChild = sChild.Trim();
170                 //sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
171                 sbJSON.Append("\"" + SafeJSON(sChild) + "\"}");
172                 id++;
173             }
174             else
175             {
176                 XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
177             }
178             sbJSON.Append(", ");
179         }
180
181         // Make a string safe for JSON
182         private string SafeJSON(string sIn)
183         {
184             StringBuilder sbOut = new StringBuilder(sIn.Length);
185             foreach (char ch in sIn)
186             {
187                 if (Char.IsControl(ch) || ch == ‘\‘‘)
188                 {
189                     //特殊字符不做处理
190                     //int ich = (int)ch;
191                     //sbOut.Append(@"\u" + ich.ToString("x4"));
192                     continue;
193                 }
194                 else if (ch == ‘\"‘ || ch == ‘\\‘ || ch == ‘/‘)
195                 {
196                     sbOut.Append(‘\\‘);
197                 }
198                 sbOut.Append(ch);
199             }
200             return sbOut.ToString();
201         }
202
203         //翻译,将英文翻译为中文。
204         private string TranslateName(string jsonName)
205         {
206             Translate g_translate = new Translate();
207             string trsName = jsonName;
208             try
209             {
210                 trsName = g_translate.DicTranslate[jsonName];
211             }
212             catch (Exception ex)
213             {
214
215             }
216             return trsName;
217         }
218
219         public bool IsReusable
220         {
221             get
222             {
223                 return false;
224             }
225         }
226     }
TranslateName()是用来做中英翻译。

3.最后效果展示:之所以没有按XML的顺序排列,是因为 SortedList 进行了排序。

				
时间: 2024-10-26 00:39:28

c# XML解析成EasyUI TreeGrid格式的相关文章

Oracle使用Sql把XML解析成表(Table)的方法

SELECT * FROM XMLTABLE('$B/DEAL_BASIC/USER_DEAL_INFO' PASSING XMLTYPE('<?xml version="1.0" encoding="gb2312" ?> <DEAL_BASIC> <USER_DEAL_INFO> <USER_DEAL_ID>1000100001</USER_DEAL_ID> <DEAL_INURE_TIME>

java XML解析成Map

1.需要解析的文件.xml 1 <?xml version="1.0" encoding="UTF-8"?> 2 <request> 3 <realName>test</realName> 4 <identityNumber>411525152242417185276</identityNumber> 5 <phone>1314456788</phone> 6 <u

字符串解析成easyui-tree的格式

传入的list: [30 : null : null, 301503 : null : null, 301501 : null : null, 301502 : null : null, 3015 : null : null] 解析后的json: 1 public class LeftTreeBean { 2 public StringBuilder getTreeMenus(List lst, String contextPath) { 3 StringBuilder model = new

自动将String类型的XML解析成实体类

package com.mooc.freemarker2dto; public class BaseDto { } package com.mooc.freemarker2dto; public class Book extends BaseDto{ private String name; private String author; private String year; private float price; public String getName() { return name;

62_json文件解析成结构体格式

package main import ( "encoding/json" "fmt") type People struct { //由于结构体生成json文本成员变量必须大写,可以使用struct_tag来二次编码,此时可以使用小写 Name string `json:"name"` Subject []string Isok bool `json:", string"` //转换成字符串类型输出 Price float6

C# 将XML格式字符串,写入数据集的表中 XML解析

将XML格式字符串,写入数据集的表1中 命名空间:using System.Xml; string strRead;//strRead为以下xml值 XmlDocument xd = new XmlDocument(); xd.LoadXml(strRead); XmlNodeList nodeList = xd.SelectSingleNode("root").ChildNodes;//获取bookstore节点的所有子节点 foreach (XmlNode xn in nodeLi

将json格式的字符串解析成Map对象

/** * 将json格式的字符串解析成Map对象 <li> * json格式:{"name":"admin","retries":"3fff","testname" * :"ddd","testretries":"fffffffff"} */ private static HashMap<String, String> t

利用Python将Linux conf配置文件的内容解析成字典格式

Linux下许多配置文件除了ini格式的可以用python的ConfigParser模块外,可以自己编写一段简单的代码将只有"key=value"这样的conf配置文件解析成字典,利用字典的key可以轻松获取key对应的value.python实现起来方法比较简单,只要逐行读取配置文件,将每一个键值对写入字典即可. python代码示例如下: #!/usr/bin/python # encoding: utf-8 # -*- coding: utf8 -*- import re fro

android XMl 解析神奇xstream 三: 把复杂对象转换成 xml

前言:对xstream不理解的请看: android XMl 解析神奇xstream 一: 解析android项目中 asset 文件夹 下的 aa.xml 文件 android XMl 解析神奇xstream 二: 把对象转换成xml 1.JavaBeen package com.android10; public class Person { String pName ; String pAge ; public String getpName() { return pName; } pub