码迷,mamicode.com
首页 > 其他好文 > 详细

xml读取类

时间:2015-09-17 01:12:07      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

public class XmlHelper<T> where T :class
    {
        XmlReader reader = null;
        public XmlHelper(string filePath)
        {
            if (File.Exists(filePath))
            {
                reader = XmlReader.Create(filePath);
            }
        }

        public List<T> ReadXmlToObject()
        {
            Type type = typeof(T);
            PropertyInfo[] fields = type.GetProperties();
            List<T> list = new List<T>();
            if (reader != null)
            {
                 XElement root = XElement.Load(reader);
                reader.Close();
                //XElement temp = root.Element(type.Name);
                //var xes = temp.Elements(type.Name);
                var xes = from temp in root.Elements() where temp.Name==type.Name select temp;
                int i = xes.Count<XElement>();
                List<XElement> list2 = null;
                if (i == 0)
                {
                    xes = from temp in root.Elements() select temp;
                     list2 = xes.ToList();
                    xes = from temp in root.Element(list2[0].Name).Elements() where temp.Name==type.Name select temp;
                }
                i = xes.Count<XElement>();
                if (i == 0)
                {
                    xes = from temp in list2[0].Elements() select temp;
                    list2 = xes.ToList();
                    xes = from temp in list2[1].Elements() where temp.Name == type.Name select temp;
                }
                i = xes.Count<XElement>();
                T t = default(T);
                foreach(var e in xes)
                {
                    t = (T)Activator.CreateInstance(type);
                    foreach (PropertyInfo info in fields)
                    {
                        var ta = e.Element(info.Name);
                        if (ta != null)
                            info.SetValue(t,ta.Value,null);
                    }
                    list.Add(t);
                }
            }

            return list;
        }
    }

xml读取类

标签:

原文地址:http://www.cnblogs.com/zjmsky/p/4815048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!