使用Xml.Linq,方便后期搜索
using System.Collections.Generic; using System.Web.Script.Serialization; using System.Xml; using System.Xml.Linq; public class ClassJsonToXML { public static XElement Json2Xml(string sJson) { JavaScriptSerializer oSerializer = new JavaScriptSerializer(); Dictionary<string, object> dict = (Dictionary<string, object>)oSerializer.DeserializeObject(sJson); XElement nRoot = new XElement("root"); foreach (var item in dict) { var element = new XElement(item.Key); KeyValue2Xml(element, item); nRoot.Add(element); } return nRoot; } private static void KeyValue2Xml(XElement node, KeyValuePair<string, object> Source) { object kValue = Source.Value; if (kValue == null) { return; } //按值类型跳转 if (kValue.GetType() == typeof(Dictionary<string, object>)) { //类型是字幕 foreach (KeyValuePair<string, object> item in kValue as Dictionary<string, object>) { var element = new XElement(item.Key); //node.OwnerDocument.CreateElement(item.Key); KeyValue2Xml(element, item); node.Add(element); } } else if (kValue.GetType() == typeof(object[])) { //类型是数组 object[] o = kValue as object[]; for (int i = 0; i < o.Length; i++) { var xitem = new XElement(node.Name);//node.OwnerDocument.CreateElement("Item"); KeyValuePair<string, object> item = new KeyValuePair<string, object>("Item", o[i]); KeyValue2Xml(xitem, item); node.Add(xitem); } } else { //类型是值 //var text = new XElement(kValue.ToString()); //node.OwnerDocument.CreateTextNode(kValue.ToString()); //node.Add(text); node.Value = kValue.ToString(); } } } |
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。