笔记:xml序列化
/// <summary> /// xml序列化 /// </summary> /// <param name="root"></param> /// <param name="dic"></param> /// <returns></returns>private static XElement XmlSerialize(string root,Dictionarydic) { XElement el = new XElement(root, dic.Select(kv => new XElement(kv.Key, kv.Value))); return el; } private static List XmlSerialize(Dictionary dic) { List list = new List (); 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 DictionaryXmlDeSerialize(string xml) { XElement rootElement; try { rootElement = XElement.Parse(xml); } catch (Exception) { return null; } Dictionary dict = new Dictionary (); 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; }