24
2022
03

json字符串转换为Xml对象(方法一)

本程序从网络上来,修正错误。在VS 2019下运行正常

using System.Collections.Generic;

using System.Web.Script.Serialization;

using System.Xml;

using System.Xml.Linq;

    public class ClassJson2Xml

    {

        /// <summary>

        /// json字符串转换为Xml对象

        /// </summary>

        /// <param name="sJson">Json字符串</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;

            if (Source.Value != null) kValue = Source.Value;

            else kValue = "";


            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(node.Name);

                    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);

            }

        }

    }


« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。