xml与json数据运用越来越广泛,根据项目的需要(xml存储不常变动的数据,json存储常用的树状结构与复杂的多字段设计,比如淘宝颜色与属性选项的功能),我把XML,JSON 都采用泛型做解析,以便数据调用的方便。现在和大家分享下xml 泛型解析。
一、创建xml模板
xml 文件名称与声明的名称一致:PayMethodBase.config
1 <?xml version="1.0" encoding="utf-8"?> 2 <ArrayOfPayMethodBase xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 3 <PayMethodBase> 4 <ID>1</ID> 5 <PayName>货到付款</PayName> 6 <IsUse>True</IsUse> 7 <Remark>送货上门后再收款,支持现金、POS机刷卡、支票支付</Remark> 8 </PayMethodBase> 9 <PayMethodBase> 10 <ID>2</ID> 11 <PayName>在线支付</PayName> 12 <IsUse>True</IsUse> 13 <Remark>即时到帐,支持绝大数银行借记卡及部分银行信用卡</Remark> 14 </PayMethodBase> 15 <PayMethodBase> 16 <ID>3</ID> 17 <PayName>邮局付款</PayName> 18 <IsUse>True</IsUse> 19 <Remark>通过快钱平台收款 汇款后1-3个工作日到账</Remark> 20 </PayMethodBase> 21 <PayMethodBase> 22 <ID>4</ID> 23 <PayName>公司转账</PayName> 24 <IsUse>True</IsUse> 25 <Remark>通过快钱平台转账 转帐后1-3个工作日内到帐</Remark> 26 </PayMethodBase> 27 </ArrayOfPayMethodBase>
二、创建model
1 [Serializable] 2 public class PayMethodBase 3 { 4 5 public Int32? ID{get;set;} 6 public String PayName{get;set;} 7 public Boolean? IsUse{get;set;} 8 public String Remark{get;set;} 9 private XPathInfo _SearchInfo = new XPathInfo(); 10 /// <summary> 11 ///辅助查询类 12 /// </summary> 13 public XPathInfo XPathInfo 14 { 15 get 16 { 17 return _SearchInfo; 18 } 19 set 20 { 21 _SearchInfo = value; 22 } 23 } 24 25 }
辅助查询类(有所省略.....)
1 [Serializable] 2 public class XPathInfo 3 { 4 5 public string OrderField {get;set;}//默认排序字段 6 private bool _orderType = false;//排序方式0降序1升序 7 public bool OrderType{ get { return _orderType; } 8 set { _orderType= value; } 9 } 10 }
二、解析模板
1 public class XmlDbHelper<T> where T : new() 2 { 3 4 private T t = new T(); 5 private XmlDocument xmlDoc = new XmlDocument(); 6 private DataSet ds = new DataSet(); 7 Encoding code = Encoding.GetEncoding("utf-8"); //编码类型 8 9 public string getXmlPath(string xmlName) 10 { 11 return Server.MapPath("~/"+xmlName + ".config"); 12 } 13 public void WriteXml(string path, T obj)//path为包含文件名的XML文件完整路径,obj为数据类型 14 { 15 XmlSerializer mySerializer = new XmlSerializer(typeof(T)); 16 StreamWriter myWriter = new StreamWriter(path, false, code); 17 mySerializer.Serialize(myWriter, obj); 18 myWriter.Close(); 19 } 20 21 public T ReadXml(string path) 22 { 23 T ob; 24 if (!System.IO.File.Exists(path)) 25 return default(T); 26 XmlSerializer mySerializer = new XmlSerializer(typeof(T)); 27 TextReader myReader = new StreamReader(path, code); 28 ob = (T)mySerializer.Deserialize(myReader); 29 myReader.Close(); 30 return ob; 31 } 32 33 /// <summary> 34 /// Decodes an attribute 35 /// </summary> 36 /// <param name="str">Attribute</param> 37 /// <returns>Decoded attribute</returns> 38 public static string XmlDecode(string str) 39 { 40 var sb = new StringBuilder(str); 41 return sb.Replace(""", "\"").Replace("'", "‘").Replace("<", "<").Replace(">", ">").Replace("&", "&").ToString(); 42 } 43 44 45 #region T GetModelXml(T obj) 获取一条信息 46 /// <summary> 47 /// 获取模型 48 /// </summary> 49 /// <returns></returns> 50 public T GetModel(T obj) 51 { 52 XPathInfo xPathInfo = (XPathInfo)obj.GetType().GetProperty("XPathInfo").GetValue(obj, null); 53 xPathInfo.GetCount = 1; 54 //把值设置 55 obj.GetType().GetProperty("XPathInfo").SetValue(obj, xPathInfo, null); 56 57 IList<T> list = this.GetList(obj); 58 if (null != list && 0 < list.Count) 59 { 60 return list[0]; 61 } 62 //return null; 63 return default(T); 64 } 65 #endregion 66 67 68 69 70 71 /// <summary> 72 /// 根据 模型获取xml记录条数 73 /// </summary> 74 /// <param name="obj"></param> 75 /// <returns></returns> 76 public int GetCount(T obj) 77 { 78 int returnVal = 0; 79 Type type = obj.GetType(); 80 string xmlName = type.Name.ToString(); 81 82 string path = getXmlPath(xmlName); 83 if (!System.IO.File.Exists(path)) 84 return 0; 85 xmlDoc.Load(path); 86 XmlNodeList xnl = xmlDoc.SelectNodes("//" + xmlName); 87 88 if (xnl.Count > 0) 89 { 90 returnVal = xnl.Count; 91 92 } 93 else 94 returnVal = 0; 95 96 return returnVal; 97 } 98 99 100 public IList<T> GetList(T ob) 101 { 102 IList<T> list = null; 103 DataTable dt = GetTable(ob); 104 if (dt != null && dt.Rows.Count > 0) 105 { 106 list = CommonDAL.DataTableToIList<T>(dt); 107 } 108 return list; 109 } 110 public DataTable GetTable(T obj) 111 { 112 XPathInfo xPathInfo = (XPathInfo)obj.GetType().GetProperty("XPathInfo").GetValue(obj, null); 113 114 Type type = obj.GetType(); 115 string xmlName = type.Name; 116 string TagName = "ArrayOf" + xmlName; 117 118 PropertyInfo[] properties = obj.GetType().GetProperties(); 119 120 121 122 string path = getXmlPath(xmlName); 123 if (!System.IO.File.Exists(path)) 124 return null; 125 126 XPathDocument doc = new XPathDocument(path); 127 128 XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator(); 129 130 131 StringBuilder strXmlPath = new StringBuilder(); 132 133 string mainField = "id,ID,iD,Id"; 134 PropertyInfo get_info = null; 135 foreach (string mm in mainField.Split(‘,‘)) 136 { 137 get_info = obj.GetType().GetProperty(mm); 138 if (null != get_info) 139 break; 140 } 141 142 143 string strOrder = get_info.Name;//默认id排序 144 StringBuilder xPath = new StringBuilder(); 145 146 if (xPathInfo != null) 147 { 148 149 if (!string.IsNullOrEmpty(xPathInfo.StrWhere.ToString()))//有搜索条件可支持模糊搜索 150 { 151 string strWhereApp = xPathInfo.StrWhere.ToString().Trim().Remove(0, 3); 152 strXmlPath.AppendFormat("/{0}/{1}[{2}]", TagName, xmlName, strWhereApp); 153 } 154 if (!string.IsNullOrEmpty(xPathInfo.OrderField)) 155 { 156 strOrder = xPathInfo.OrderField; 157 } 158 159 if (string.IsNullOrEmpty(xPathInfo.StrWhere.ToString()))//无搜索条件的时候默认只能查询一个字段 160 { 161 foreach (PropertyInfo info in properties) 162 { 163 if (info.GetValue(obj, null) != null && DBNull.Value != info.GetValue(t, null) 164 && !info.Name.ToLower().Equals("id") && !info.Name.ToLower().Equals("xpathinfo")) 165 { 166 167 xPath.AppendFormat(" [contains({0},‘{1}‘)]", info.Name, info.GetValue(obj, null)); 168 } 169 if (info.Name.ToLower().Equals("id") && info.GetValue(obj, null) != null) //给GetModelXml专用 170 { 171 xPath.AppendFormat("[{0}=‘{1}‘]", info.Name, info.GetValue(obj, null)); 172 } 173 } 174 strXmlPath.AppendFormat("//{0}{1}", xmlName, xPath.ToString()); 175 } 176 177 } 178 else //没加入XPathInfo参数的时候 只能查询一个字段 179 { 180 foreach (PropertyInfo info in properties) 181 { 182 if (info.GetValue(obj, null) != null && DBNull.Value != info.GetValue(t, null) && !info.Name.ToLower().Equals("id")) 183 { 184 xPath.AppendFormat("[contains({0},‘{1}‘)]", info.Name, info.GetValue(obj, null)); 185 } 186 } 187 strXmlPath.AppendFormat("//{0}{1}", xmlName, xPath.ToString()); 188 189 } 190 // XPathNodeIterator iter = nav.Select(strXmlPath.ToString());//"//" + xmlName + "[contains(str1,‘0‘)]"); 191 DataTable tab = new DataTable(); 192 193 // throw new Exception(strXmlPath.ToString()+" order:"+strOrder); 194 if (xPathInfo.IsShowXpath) 195 { 196 throw new Exception("xpath:" + strXmlPath.ToString() + " order by [" + strOrder + "] " + (xPathInfo.OrderType == false ? " desc" : "asc")); 197 } 198 199 //throw new Exception("xpath:" + strXmlPath.ToString() + " order by [" + strOrder + "] " + (xPathInfo.OrderType == false ? " desc" : "asc"));//strXmlPath.ToString()); 200 XPathExpression exp = nav.Compile(strXmlPath.ToString());//xpath 排序 201 202 203 204 exp.AddSort(strOrder, (xPathInfo.OrderType == false) ? XmlSortOrder.Descending : XmlSortOrder.Ascending, 205 XmlCaseOrder.None, "", getXmlTypeIsInt(obj, strOrder) ? XmlDataType.Number : XmlDataType.Text); 206 207 208 XPathNodeIterator iter = nav.Select(exp); //查询数据 209 foreach (PropertyInfo Info in properties) 210 { 211 if (!Info.Name.ToLower().Equals("xpathinfo")) 212 tab.Columns.Add(Info.Name); 213 214 } 215 int count = 0;//设置条数 216 while (iter.MoveNext()) 217 { 218 count++; 219 DataRow dr = tab.NewRow(); 220 foreach (PropertyInfo Info in properties) 221 { 222 XPathNavigator newIter = iter.Current.SelectSingleNode(Info.Name); 223 224 if (!Info.Name.ToLower().Equals("xpathinfo")) 225 { 226 227 try 228 { 229 dr[newIter.Name] = !string.IsNullOrEmpty(newIter.Value.ToString()) ? newIter.Value : ""; 230 } 231 catch { } 232 233 } 234 } 235 236 tab.Rows.Add(dr); 237 238 // if (xPathInfo.GetCount == 0) 239 //continue; 240 if (xPathInfo.GetCount != 0 && xPathInfo.GetCount <= count) 241 break; 242 } 243 tab.TableName = xmlName; 244 return tab; 245 246 247 } 248 249 250 251 }
实例调用:
1 PayMethodBase pmMol = new PayMethodBase(); 2 pmMol.ID = 1; 3 pmMol = new XmlDbHelper<PayMethodBase>().GetModel(pmMol); 4 if(pmMol !=null){ 5 Response.Write(pmMol.PayName); 6 }
时间: 2024-10-29 19:08:55