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 进行了排序。