C#将XML与JSON数据的互相转换
1、xml转json
string xml = "<Test><Name>Test class</Name><X>100</X><Y>200</Y></Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc); Console.WriteLine("XML -> JSON: {0}", json); Console.ReadLine();
2、json转xml
//方法1 XmlDocument doc1 = JsonConvert.DeserializeXmlNode(json); Console.WriteLine(doc1.OuterXml); //方法2 //json字符串需要把键加"才行 如:{Name:"aaa",Value:1} 这里Name和Value是键这样写法转换的时候报错 需要写成 {"Name":"aaa","Value":1} XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max); XmlDocument doc2 = new XmlDocument(); doc2.Load(reader); //方法3 /// <summary> /// json字符串转换为Xml对象 /// </summary> /// <param name="sJson"></param> /// <returns></returns> public static XmlDocument Json2Xml(string sJson) { JavaScriptSerializer oSerializer = new JavaScriptSerializer(); Dictionary<string, object> Dic = (Dictionary<string, object>)oSerializer.DeserializeObject(sJson); XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDec; xmlDec = doc.CreateXmlDeclaration("1.0", "gb2312", "yes"); doc.InsertBefore(xmlDec, doc.DocumentElement); XmlElement nRoot = doc.CreateElement("root"); doc.AppendChild(nRoot); foreach (KeyValuePair<string, object> item in Dic) { XmlElement element = doc.CreateElement(item.Key); KeyValue2Xml(element, item); nRoot.AppendChild(element); } return doc; } private static void KeyValue2Xml(XmlElement node, KeyValuePair<string, object> Source) { object kValue = Source.Value; if (kValue.GetType() == typeof(Dictionary<string, object>)) { foreach (KeyValuePair<string, object> item in kValue as Dictionary<string, object>) { XmlElement element = node.OwnerDocument.CreateElement(item.Key); KeyValue2Xml(element, item); node.AppendChild(element); } } else if (kValue.GetType() == typeof(object[])) { object[] o = kValue as object[]; for (int i = 0; i < o.Length; i++) { XmlElement xitem = node.OwnerDocument.CreateElement("Item"); KeyValuePair<string, object> item = new KeyValuePair<string, object>("Item", o[i]); KeyValue2Xml(xitem, item); node.AppendChild(xitem); } } else { XmlText text = node.OwnerDocument.CreateTextNode(kValue.ToString()); node.AppendChild(text); } }