标签:
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; } }
标签:
原文地址:http://www.cnblogs.com/zjmsky/p/4815048.html