首页 > Windows开发 > 详细

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

时间:2019-04-10 14:05:36      阅读:263      评论:0      收藏:0      [点我收藏+]

  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;
        }

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!