【C#】【Demo】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
原文地址:https://www.cnblogs.com/lanofsky/p/10644454.html