参考地址:https://www.cnblogs.com/Shang0109/archive/2013/07/09/3180026.html
在这上面做了个改进,把第一个方法改成了泛型方法
Code
public static List<T> galigaygay<T>(string xmlStrSource)
{
List<T> dataList = new List<T>();
try
{
Type t = typeof(T);
object obj = Activator.CreateInstance(t, null);//创建指定类型实例
PropertyInfo[] fields = obj.GetType().GetProperties();//获取指定对象的所有公共属性
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlStrSource);//加载xml
XmlNodeList xlist = xml.GetElementsByTagName("Item");//获取Item节点列表
foreach (XmlNode xn in xlist)//遍历Item节点下的子节点
{
object u = Activator.CreateInstance(t, null);//创建指定类型实例
foreach (PropertyInfo p in fields)
{
for (int i = 0; i < xn.ChildNodes.Count;)
{
if (xn.ChildNodes[i].Name == p.Name)
{
p.SetValue(u, xn.ChildNodes[i].InnerText, null);//给创建的实例属性赋值
}
i++;
}
}
dataList.Add((T)u);
}
}
catch (Exception ex)
{
throw ex;
}
return dataList;
}
原文:https://www.cnblogs.com/Mxy-cnblog/p/11776804.html