public sealed class XMLSerilizable { ////// XML转换为对象 /// ////// /// public static T XMLToObject (string xml) where T : new() { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode root = doc.FirstChild; Dictionary table = new Dictionary (); foreach (XmlNode v in root.ChildNodes) { table.Add(v.Name, GetValue(v)); } return DicToObject (table); //new RequestText(table); } /// /// 字典类型转化为对象 /// /// ///private static T DicToObject (Dictionary dic) where T : new() { var md = new T(); DicToObject(md, dic); return md; } /// /// Dictionary填充对象 /// /// /// private static void DicToObject(object md, System.Collections.IDictionary dic) { foreach (var filed in dic.Keys) { BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance; try { var value = dic[filed]; if (value is System.Collections.IDictionary) { Type ct = md.GetType().GetProperty(filed + "", flag).PropertyType; object o = Activator.CreateInstance(ct); DicToObject(o, value as System.Collections.IDictionary); md.GetType().GetProperty(filed + "", flag).SetValue(md, o, null); } else md.GetType().GetProperty(filed + "", flag).SetValue(md, value, null); } catch (Exception e) { } } // return md; } ////// 获得节点值 /// /// ///private static object GetValue(XmlNode node) { if (node.HasChildNodes) { // 这种结构 node.ChildNodes.Count==1 if (node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType != XmlNodeType.Element) { return node.InnerText; } else { Dictionary table = new Dictionary (); foreach (XmlNode n in node.ChildNodes) { table.Add(n.Name, GetValue(n)); } return table; } } return node.InnerText; } }