C#将XML字符串转换成实体对象,并去除cdata <xml><ToUserName><![CDATA[gh_8b13cf658f77]]></ToUserName>
<FromUserName><![CDATA[oBvnj5v9LlSagr_XjCLChg7acR30]]></FromUserName>
<CreateTime>1639555238</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[subscribe]]></Event>
<EventKey><![CDATA[]]></EventKey></xml>
如上xml字符串是关注公众时,返回的数据
public static T GetXmlModel<T>(T model, string xmlString) where T : class
{
try
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlString);//把xml格式的字符串转为XMLDataDocument对象
Dictionary<string, string> xmlDic = new Dictionary<string, string>();
字符串截取对象XmlNodeList data = xml.DocumentElement.ChildNodes;//得到的是xml对象的节点数组
for (int i = 0; i < data.Count; i++)
{
xmlDic.Add(data.Item(i).LocalName, data.Item(i).InnerText);
}
var m = model.GetType();
foreach (PropertyInfo p in m.GetProperties())
{
string name = p.Name;
if (xmlDic.Keys.Contains(name))
{
string value = xmlDic.Where(x => x.Key == name).FirstOrDefault().Value;
p.SetValue(model,
string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, p.PropertyType), null);
}
}
return model;
}
catch (Exception ex)
{
return model;
}
}
调⽤⽅法
var param = new XMLModel();
string bodyStr=@"<xml><ToUserName><![CDATA[gh_8b13cf658f77]]></ToUserName>
<FromUserName><![CDATA[oBvnj5v9LlSagr_XjCLChg7acR30]]></FromUserName>
<CreateTime>1639555238</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[subscribe]]></Event>
<EventKey><![CDATA[]]></EventKey>";
var obj=GetModel<XMLModel>(param, bodyStr);
实体类
public class XMLModel
{
///<summary>
///
///</summary>
public string FromUserName { get; set; }
///<summary>
///
/
//</summary>
public string CreateTime { get; set; }
///<summary>
///
///</summary>
public string MsgType { get; set; }
///<summary>
///
///</summary>
public string Event { get; set; }
///<summary>
/
//
///</summary>
public string EventKey { get; set; }    }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。