企业微信 接收回调事件,XML需要反序列化成实体类,自己写了一个,因为没有子节点所有适用
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T DeserailizeXML<T>(string xml)
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlElement rootElement = doc.DocumentElement;
Type type = typeof(T);
//使用表达式 Expression 创建对象
NewExpression constructorExpression = Expression.New(typeof(T));
Expression<Func<T>> lambdaExpression = Expression.Lambda<Func<T>>(constructorExpression);
Func<T> func = lambdaExpression.Compile();
T newEntity = func();
//使用反射创建对象
// T newEntity = Activator.CreateInstance<T>();
PropertyInfo[] propertyInfos = type.GetProperties();
for (int i = 0; i < propertyInfos.Length; i++)
{
PropertyInfo propertyInfo = propertyInfos[i];
if (rootElement.SelectSingleNode(propertyInfo.Name) == null) continue;
try
{
propertyInfo.SetValue(newEntity, !string.IsNullOrEmpty(rootElement.SelectSingleNode(propertyInfo.Name).InnerText) ? Convert.ChangeType(rootElement.SelectSingleNode(propertyInfo.Name).InnerText, propertyInfo.PropertyType) : rootElement.SelectSingleNode(propertyInfo.Name).InnerText);
}
catch
{
}
}
return newEntity;
}
catch (Exception ex)
{
throw ex;
}
}