欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【C#】【对象转XML】xml序列化

程序员文章站 2022-03-20 09:37:41
笔记:xml序列化 /// /// xml序列化 /// /// /// /// private stati ......

笔记:xml序列化


        /// <summary>
        /// xml序列化
        /// </summary>
        /// <param name="root"></param>
        /// <param name="dic"></param>
        /// <returns></returns>

        private static xelement xmlserialize(string root,dictionary<string, object> dic)
        {
           
            xelement el = new xelement(root,
            dic.select(kv => new xelement(kv.key, kv.value)));
            return el;
        }

        private static list<xelement> xmlserialize(dictionary<string, object> dic)
        {
            list<xelement> list = new list<xelement>();
            foreach (var item in dic)
            {
                list.add(new xelement(item.key, item.value));
            }
            return list;
        }

 

序列化使用示例

 dictionary<string, object> apigdic = new dictionary<string, object>();

 dictionary<string, object> paramdic= new dictionary<string, object>();

 dictionary<string, object> transdic= new dictionary<string, object>();

apigdic.add("info", xmlserialize(paramdic));
apigdic.add("trans", xmlserialize(transdic));
string xmlstr = xmlserialize("apig",apigdic).tostring();

 

反序列化:

private static dictionary<string, object> xmldeserialize(string xml)
        {
            xelement rootelement;
            try
            {
                 rootelement = xelement.parse(xml);
            }
            catch (exception)
            {
                return null;
            }

            dictionary<string, object> dict = new dictionary<string, object>();
            foreach (var el in rootelement.elements())
            {
                
                var el2=xmldeserialize(el.tostring());
                if (el2 == null || el2.count==0)
                    dict.add(el.name.localname, el.value);
                else
                    dict.add(el.name.localname, el2);
            }
            return dict;
        }