设为首页 加入收藏

TOP

【C#】【对象转XML】xml序列化
2019-09-17 18:58:18 】 浏览:36
Tags:对象 XML xml 序列化

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

 

序列化使用示例

 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;
        }
View Code

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇深度长文-我花了10天时间造了个轮.. 下一篇ServiceStack 多租户的实现方案

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目