【C#】【对象转XML】xml序列化(转载:小牛导航,super-nb)

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

更多NET精彩资源
链接:https://pan.baidu.com/s/1tmlqOFOoFZdWp2uuRHNRrQ 
提取码:fdeb

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值