将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;
}
浙公网安备 33010602011771号