public sealed class XMLSerilizable { /// <summary> /// XML转换为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xml"></param> /// <returns></returns> public static T XMLToObject<T>(string xml) where T : new() { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode root = doc.FirstChild; Dictionary<string, object> table = new Dictionary<string, object>(); foreach (XmlNode v in root.ChildNodes) { table.Add(v.Name, GetValue(v)); } return DicToObject<T>(table); //new RequestText(table); } /// <summary> /// 字典类型转化为对象 /// </summary> /// <param name="dic"></param> /// <returns></returns> private static T DicToObject<T>(Dictionary<string, object> dic) where T : new() { var md = new T(); DicToObject(md, dic); return md; } /// <summary> /// Dictionary填充对象 /// </summary> /// <param name="md"></param> /// <param name="dic"></param> 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; } /// <summary> /// 获得节点值 /// </summary> /// <param name="node"></param> /// <returns></returns> private static object GetValue(XmlNode node) { if (node.HasChildNodes) { // <MsgType><![CDATA[text]]></MsgType> 这种结构 node.ChildNodes.Count==1 if (node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType != XmlNodeType.Element) { return node.InnerText; } else { Dictionary<string, object> table = new Dictionary<string, object>(); foreach (XmlNode n in node.ChildNodes) { table.Add(n.Name, GetValue(n)); } return table; } } return node.InnerText; } }