参考地址:https://www.cnblogs.com/Shang0109/archive/2013/07/09/3180026.html
在这上面做了个改进,把第一个方法改成了泛型方法
Code
private static List<T> galigaygay<T>(string xmlStrSource, string xmlNodeName)
{
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(xmlNodeName);//获取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].Attributes["name"].Value.Equals(p.Name,StringComparison.OrdinalIgnoreCase))
{
p.SetValue(u, xn.ChildNodes[i].Attributes["value"].Value, null);//给创建的实例属性赋值
}
i++;
}
}
dataList.Add((T)u);
}
}
catch (Exception ex)
{
throw ex;
}
return dataList;
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<list>
<R>
<item name = "XM" name_cn = "姓名" value = "1"/>
<item name = "XB" name_cn = "性别" value = "ee"/>
</R>
<R>
<item name = "XM" name_cn = "姓名" value = "2"/>
<item name = "XB" name_cn = "性别" value = "rr"/>
</R>
</list>
调用
List<实体类> list=galigaygay<实体类>(xmlstr,"R")