代码改变世界

将Xml转为对象

2020-07-26 09:53  idea555  阅读(368)  评论(0)    收藏  举报

public static T XmlToObject<T>(string xml) where T : new()
{
//获得所有节点
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);
XmlElement root = xdoc.DocumentElement;
XmlNodeList nodeList = root.ChildNodes;

T returnObject = new T();
Type type = typeof(T);

//遍历节点赋值
foreach (XmlNode node in nodeList)
{
XmlElement xe = (XmlElement)node;
PropertyInfo propInfo = type.GetProperty(xe.Name);

if (propInfo != null)
{
string value = xe.InnerText;
propInfo.SetValue(returnObject, value, null);
}
}

return returnObject;
}