/// <summary>
///
/// </summary>
/// <typeparam name="T">要反射的类名称 CLASS</typeparam>
/// <param name="xml">要解析的XML</param>
/// <param name="subNode">解析的路径</param>
/// <param name="cordysnamespace">XML中带有的命名空间命名空间数组0为命名空间名称数组1为命名空间值</param>
/// <returns>返回实体类的集合</returns>
public static T XmlToObj<T>(string xml,string subNode,string[] cordysnamespace) where T : new()
{
//XmlDocument装载xml内容
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
//命名空间管理器,把依次要访问的结点的所有父命结点名空间
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NaMetable);
nsmgr.AddNamespace("SOAP","http://schemas.xmlsoap.org/soap/envelope/"); //有命名空间名称的直接添加
nsmgr.AddNamespace("cordys","http://schemas.cordys.com/USER_INFO"); //没有命名空间名称的任意指定一个,但是该名称需要与xpath中字符相同。
XmlNode node = doc.SelectSingleNode(subNode,nsmgr);//使用SelectSingleNode方法选择结点
//使用反射转换成实体
T entity = new T();
Type objtype = typeof(T);
PropertyInfo[] propinfos = objtype.GetProperties();
//填充entity类的属性
foreach (PropertyInfo propinfo in propinfos)
{
string v = node.SelectSingleNode("",nsmgr).InnerText;
if (v != null)
{
propinfo.SetValue(entity,Convert.ChangeType(v,propinfo.PropertyType),null);
}
} return entity;
}
参数补充说明:
xml内容------------------------------------------------
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Header xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
....
</SOAP:Header>
<SOAP:Body>
<getUserInfoByAccountResponse xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://schemas.cordys.com/USER_INFO">
<tuple>
<USER_INFO>
<USER_ID>777</USER_ID>
<ERPID>0</ERPID>>
<POSITION>项目经理</POSITION>
</USER_INFO>
</tuple>
</getUserInfoByAccountResponse>
</SOAP:Body>
</SOAP:Envelope>
T-------------------------------------------
UserInfo
UserInfo的定义
public class UserInfo
{
public string USER_ID { get; set; }
public string ERPID { set; get; }
public string POSITION { set; get; }
}
subNode-------------------------------------------
"SOAP:Envelope/SOAP:Body/cordys:getUserInfoByAccountResponse/cordys:tuple/cordys:USER_INFO"
cordysnamespace------------------------------------
string[] cordysnamespace=new string[2]{"cordys","http://schemas.cordys.com/USER_INFO"}