XML 字符串解析
微信红包发送完成后返回xml字符串,解析过程如下:
1、调用解析:
public ActionResult GetEntityFromXml() { string str = @"<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[帐号余额不足,请到商户平台充值后再重试]]></return_msg> <result_code><![CDATA[FAIL]]></result_code> <err_code><![CDATA[NOTENOUGH]]></err_code> <err_code_des><![CDATA[帐号余额不足,请到商户平台充值后再重试]]></err_code_des> <mch_billno><![CDATA[20170114130807a1234567]]></mch_billno> <mch_id><![CDATA[**********]]></mch_id> <wxappid><![CDATA[wx****************]]></wxappid> <re_openid><![CDATA[oPg_***********************]]></re_openid> <total_amount>100</total_amount> </xml>"; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(str); var rmodel = new WeiXinRedPackgeResultModel(); Html_Tools.Class1.GetEntityFromXml<WeiXinRedPackgeResultModel>(rmodel, doc); return Json(rmodel); }
2、解析类(可完善通用):
public static class Class1 { public static void GetEntityFromXml<T>(this T entity, System.Xml.XmlDocument doc) { Dictionary<string, string> Dic = new Dictionary<string, string>(); System.Xml.XmlNodeList nodelist = doc.DocumentElement.ChildNodes; if (nodelist.Count > 0) { Type t = entity.GetType(); foreach (System.Xml.XmlElement el in nodelist)//读元素值 { System.Reflection.PropertyInfo proInfo = t.GetProperty(el.Name);//访问Obj的类型的属性Value的属性信息(propertyInfo) if (proInfo != null) { string str2 = proInfo.PropertyType.Name; if (str2 == null) { goto Label_018A; } if (!(str2 == "DateTime")) { if (str2 == "Boolean") { goto Label_00E9; } if (str2 == "Int64") { goto Label_0134; } goto Label_018A; } proInfo.SetValue(entity, new DateTime(long.Parse(el.InnerText)), null); } continue; Label_00E9: proInfo.SetValue(entity, el.InnerText == "1", null); continue; Label_0134: proInfo.SetValue(entity, long.Parse(el.InnerText), null); continue; Label_018A: proInfo.SetValue(entity, el.InnerText, null); } } } }
3、返回的实体类:
public class WeiXinRedPackgeResultModel { #region 微信红包返回值 public string return_code { get; set; } public string return_msg { get; set; } public string result_code { get; set; } public string err_code { get; set; } public string err_code_des { get; set; } public string mch_billno { get; set; } public string mch_id { get; set; } public string wxappid { get; set; } public string re_openid { get; set; } #endregion }