当前位置: 移动技术网 > IT编程>开发语言>.net > 【C#】【对象转XML】xml序列化

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

2019年04月03日  | 移动技术网IT编程  | 我要评论

公主恋人ova 下卷,sd高达g世纪seed,1518手机

笔记: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;
        }

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网