C# XML反序列化解析成对象集合
1.需要解析的XML字符串,获取 BookedInfo 集合
string xmlStr = @"<Request> <BookedInfos> <BookedInfo> <CHARGECODE> 收费项编码 </CHARGECODE> <HISDEPTCODE> His科室代码 </HISDEPTCODE> <INQTY> 出库数量 </INQTY> </BookedInfo> <BookedInfo> <CHARGECODE> 收费项编码 </CHARGECODE> <HISDEPTCODE> His科室代码 </HISDEPTCODE> <INQTY> 出库数量 </INQTY> </BookedInfo> </BookedInfos> </Request>";
2.需要解析成的目标实体类
public class BookedInfo { public string CHARGECODE { get; set; } public string HISDEPTCODE { get; set; } public string INQTY { get; set; } }
3.解析的帮助方法
/// <summary> /// XML转对象集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xmlStr"></param> /// <param name="nodename"></param> /// <returns></returns> public static List<T> XmlUrlConvertModel<T>(string xmlStr, string nodename) where T : class, new() { List<T> ts = new List<T>(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlStr); XmlNodeList xmlNodeList = xmlDoc.SelectNodes(nodename); foreach (XmlNode xnls in xmlNodeList) { T t = new T(); foreach (XmlNode xnl in xnls.ChildNodes) { PropertyInfo[] propertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo pinfo in propertyInfo) { if (xnl.Name.ToUpper() == pinfo.Name.ToUpper()) { pinfo.SetValue(t, xnl.InnerText, null); break; } } } ts.Add(t); } return ts; }
4.调用帮助方法
object obj = new object(); List<BookedInfo> ls = new List<BookedInfo>(); try { ls = ObjHelper.XmlUrlConvertModel<BookedInfo>(xml, "Request/BookedInfos/BookedInfo"); } catch (Exception) { obj = new { code = -1, message = "未能识别xml,请校验!" }; return JsonConvert.SerializeObject(obj); }
5.结果