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; }

    }

 

 

 

 

 

posted @ 2021-12-23 14:38  汪小让  阅读(1299)  评论(0编辑  收藏  举报