【C#】【对象转XML】xml序列化
程序员文章站
2022-06-28 21:19:28
笔记:xml序列化 /// /// xml序列化 /// /// /// /// private stati ......
笔记: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; }
上一篇: 到深圳出差的时间
下一篇: 58VIP账号发贴器