c#怎么将json转换成xml

2025-04-28 23:34:45
推荐回答(1个)
回答1:

  ///   
        /// json字符串转换为Xml对象  
        /// 
  
        ///   
        ///   
        public static XmlDocument Json2Xml(string sJson)  
        {  
            //XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(sJson), XmlDictionaryReaderQuotas.Max);  
            //XmlDocument doc = new XmlDocument();  
            //doc.Load(reader);  
  
            JavaScriptSerializer oSerializer = new JavaScriptSerializer();  
            Dictionary Dic = (Dictionary)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 item in Dic)  
            {  
                XmlElement element = doc.CreateElement(item.Key);  
                KeyValue2Xml(element, item);  
                nRoot.AppendChild(element);  
            }  
            return doc;  
        }  
  
        private static void KeyValue2Xml(XmlElement node, KeyValuePair Source)  
        {  
            object kValue = Source.Value;  
            if (kValue.GetType() == typeof(Dictionary))  
            {  
                foreach (KeyValuePair item in kValue as Dictionary)  
                {  
                    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 item = new KeyValuePair("Item", o[i]);  
                    KeyValue2Xml(xitem, item);  
                    node.AppendChild(xitem);  
                }  
                     
            }  
            else  
            {  
                XmlText text = node.OwnerDocument.CreateTextNode(kValue.ToString());  
                node.AppendChild(text);  
            }  
        }