C# 将对应的xml文档赋值给指定模型(对象)

  public static IList<T> XmlToEntityList<T>(string xml) where T : new()
        {
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.LoadXml(xml);
            }
            catch(Exception ex)
            {
                ex.ToString().LogAllRecord();
                return null;
            }

return  EINModel<T>(doc);

}

private static IList<T> EINModel<T>(XmlDocument doc) where T : new()
        {
            XmlNode node = doc.ChildNodes[1];
            if (node == null) { return null; }
            XmlNode subNode = node.ChildNodes[1];
            IList<T> items = new List<T>();
            foreach (XmlNode a in subNode.ChildNodes)
            {
                items.Add(XmlNodeToEntity<T>(a));
            }
            return items;
        }

        private static T XmlNodeToEntity<T>(XmlNode node) where T : new()
        {
            T item = new T();

            if (node.NodeType == XmlNodeType.Element)
            {
                XmlElement element = (XmlElement)node;

                System.Reflection.PropertyInfo[] propertyInfo =
            typeof(T).GetProperties(System.Reflection.BindingFlags.Public |
            System.Reflection.BindingFlags.Instance);

                foreach (XmlNode attr in element.ChildNodes)
                {
                    foreach (System.Reflection.PropertyInfo pinfo in propertyInfo)
                    {
                        if (pinfo != null)
                        {
                            if (pinfo.Name.ToLower() == attr.Name.ToLower())
                            {
                                pinfo.SetValue(item, attr.InnerText, null);
                                break;
                            }
                        }
                    }

                }
            }
            return item;
        }

原文地址:https://www.cnblogs.com/LuoEast/p/10683020.html