通用的 XML 操作类

  1     /// <summary>
  2     /// 通用的 XML 操作类 (微型本地xml数据库)
  3     /// </summary>
  4     /// <typeparam name="T"></typeparam>
  5     class XmlUtils<T>
  6     {
  7         /// <summary>
  8         /// xml 保存路径
  9         /// </summary>
 10         private static readonly String xmlPath = @"data\";
 11         /// <summary>
 12         /// 主键名
 13         /// </summary>
 14         public static readonly String primaryPropertyName = "Id";
 15 
 16 
 17         /// <summary>
 18         /// 创建xml文件
 19         /// </summary>
 20         /// <param name="t"></param>
 21         public static void CreateXMLFile(T t)
 22         {
 23             String className = ReflectionUtils<T>.GetClassName(t);
 24             XmlDocument xmldoc = new XmlDocument();
 25 
 26             //加入XML的声明段落
 27             XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"", "");
 28             xmlnode.Value = "version=\"1.0\" encoding=\"utf-8\"";
 29             xmldoc.AppendChild(xmlnode);
 30 
 31             //加入一个根元素
 32             XmlElement xmlelem = xmldoc.CreateElement("Root");
 33             //XmlText xmltext = xmldoc.CreateTextNode ( "Root Text" ) ;
 34             //xmlelem.AppendChild ( xmltext ) ;
 35             xmldoc.AppendChild(xmlelem);
 36             if (!Directory.Exists(xmlPath))
 37             {
 38                 Directory.CreateDirectory(xmlPath);
 39             }
 40             xmldoc.Save(xmlPath + className + ".xml");
 41         }
 42 
 43         /// <summary>
 44         /// 判断主键是否唯一
 45         /// </summary>
 46         /// <param name="xmldoc"></param>
 47         /// <param name="className"></param>
 48         /// <param name="o"></param>
 49         /// <returns></returns>
 50         private static Boolean IsPrimaryKeyUnique(XmlDocument xmldoc,String className,Object o)
 51         {
 52             String xPathStr = "Root/" + className + "[" + primaryPropertyName + "='"+ o.ToString() +"']";
 53             // XPath 查询
 54             XmlNodeList nodeList = xmldoc.SelectNodes(xPathStr);
 55             if (nodeList.Count > 0)
 56             {
 57                 return false;
 58             }
 59             else
 60             {
 61                 return true;
 62             }
 63          
 64         }
 65 
 66         /// <summary>
 67         /// 插入对象
 68         /// </summary>
 69         /// <param name="t"></param>
 70         public static void InsertXmlItem(T t)
 71         {
 72             String className = ReflectionUtils<T>.GetClassName(t);
 73             XmlDocument xmldoc = new XmlDocument();
 74             //加载xml文件
 75             try
 76             {
 77                 xmldoc.Load(xmlPath + className + ".xml");
 78             }
 79             catch (Exception e)
 80             {
 81 
 82                 Console.WriteLine(e.Message);
 83             }
 84 
 85             //判断 主键号是否有值 或者 主键已经存在
 86             Object o = ReflectionUtils<T>.GetTPropertyValue(t, primaryPropertyName);
 87             if (o != null && IsPrimaryKeyUnique(xmldoc, className, o))
 88             {
 89                 //获取根节点
 90                 XmlNode root = xmldoc.DocumentElement;
 91                 //创建子节点
 92                 XmlElement itemNode = xmldoc.CreateElement(className);
 93 
 94                 PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t);
 95                 foreach (PropertyInfo propertyInfo in propertyInfos)
 96                 {
 97                     String propertyName = propertyInfo.Name;
 98                     String propertyValue = propertyInfo.GetValue(t, null) == null ? "" : propertyInfo.GetValue(t, null).ToString();
 99                     XmlElement propertyNode = xmldoc.CreateElement(propertyName);
100                     propertyNode.InnerText = propertyValue;
101                     itemNode.AppendChild(propertyNode);
102                 }
103                 root.AppendChild(itemNode);
104                 xmldoc.Save(xmlPath + className + ".xml");
105             }
106             else
107             {
108                 throw new Exception("插入数据失败,插入的主键为空或者主键已经存在。");
109             }
110             
111             
112         }
113 
114         /// <summary>
115         /// 批量插入对象
116         /// </summary>
117         /// <param name="list"></param>
118         public static void BatchInsertXmlItem(List<T> list)
119         {
120             String className = typeof(T).Name;
121             XmlDocument xmldoc = new XmlDocument();
122             //加载xml文件
123             try
124             {
125                 xmldoc.Load(xmlPath + className + ".xml");
126             }
127             catch (Exception e)
128             {
129 
130                 Console.WriteLine(e.Message);
131             }
132             //获取根节点
133             XmlNode root = xmldoc.DocumentElement;
134             
135             foreach (T t in list)
136             {
137                 //创建子节点
138                 XmlElement itemNode = xmldoc.CreateElement(className);
139                 PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t);
140                 foreach (PropertyInfo propertyInfo in propertyInfos)
141                 {
142                     String propertyName = propertyInfo.Name;
143                     String propertyValue = propertyInfo.GetValue(t, null) == null ? "" : propertyInfo.GetValue(t, null).ToString();
144                     XmlElement propertyNode = xmldoc.CreateElement(propertyName);
145                     propertyNode.InnerText = propertyValue;
146                     itemNode.AppendChild(propertyNode);
147                 }
148                 root.AppendChild(itemNode);
149             }
150             
151             xmldoc.Save(xmlPath + className + ".xml");
152         }
153 
154         /// <summary>
155         /// 更新对象
156         /// </summary>
157         /// <param name="t"></param>
158         public static void UpdateXmlItem(T t)
159         {
160             String className = ReflectionUtils<T>.GetClassName(t);
161             XmlDocument xmldoc = new XmlDocument();
162             //加载xml文件
163             try
164             {
165                 xmldoc.Load(xmlPath + className + ".xml");
166             }
167             catch (Exception e)
168             {
169                 Console.WriteLine(e.Message);
170             }
171             // 拼接 XML XPath 查询字符串 
172             String xPathStr = "Root/" + className + "[" + primaryPropertyName + "='" + ReflectionUtils<T>.GetTPropertyValue(t, primaryPropertyName) + "']";
173             // XPath 查询
174             XmlNodeList nodes = xmldoc.SelectNodes(xPathStr);
175             if (nodes.Count > 0)
176             {
177                 foreach (XmlNode xmlNode in nodes)
178                 {
179                     XmlElement xmlElement = (XmlElement)xmlNode;
180                     // 属性遍历
181                     PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t);
182                     foreach (PropertyInfo propertyInfo in propertyInfos)
183                     {
184                         String propertyName = propertyInfo.Name;
185                         String propertyValue = propertyInfo.GetValue(t, null) == null ? "" : propertyInfo.GetValue(t, null).ToString();
186                         // 更新
187                         xmlElement.SelectSingleNode(propertyName).InnerText = propertyValue;
188                     }
189                 }
190                 // 保存
191                 xmldoc.Save(xmlPath + className + ".xml");
192             }
193         }
194 
195         /// <summary>
196         /// 删除对象
197         /// </summary>
198         /// <param name="t"></param>
199         public static void DeleteXMLItem(T t)
200         {
201             String className = ReflectionUtils<T>.GetClassName(t);
202             XmlDocument xmldoc = new XmlDocument();
203             //加载xml文件
204             try
205             {
206                 xmldoc.Load(xmlPath + className + ".xml");
207             }
208             catch (Exception e)
209             {
210                 Console.WriteLine(e.Message);
211             }
212             // 拼接 XML XPath 查询字符串 
213             String xPathStr = "Root/" + className + "[" + primaryPropertyName + "='" + ReflectionUtils<T>.GetTPropertyValue(t, primaryPropertyName) + "']";
214             // XPath 查询
215             XmlNodeList nodes = xmldoc.SelectNodes(xPathStr);
216             if (nodes.Count > 0)
217             {
218                 foreach (XmlNode xmlNode in nodes)
219                 {
220                     xmlNode.ParentNode.RemoveChild(xmlNode);
221                 }
222                 xmldoc.Save(xmlPath + className + ".xml");
223             }
224         }
225 
226         /// <summary>
227         /// 获取所有对象
228         /// </summary>
229         /// <returns></returns>
230         public static List<T> GetList()
231         {
232             List<T> list = new List<T>();
233             String className = typeof(T).Name;
234             XmlDocument xmldoc = new XmlDocument();
235             //加载xml文件
236             try
237             {
238                 xmldoc.Load(xmlPath + className + ".xml");
239             }
240             catch (Exception e)
241             {
242                 Console.WriteLine(e.Message);
243             }
244             XmlNodeList nodeList = xmldoc.GetElementsByTagName(className);
245             foreach (XmlNode xmlNode in nodeList)
246             {
247                 T t = Activator.CreateInstance<T>();
248                 XmlElement xmlElement = (XmlElement)xmlNode;
249                 // 属性遍历
250                 PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t);
251                 foreach (PropertyInfo propertyInfo in propertyInfos)
252                 {
253                     String propertyName = propertyInfo.Name;
254                     ReflectionUtils<T>.SetTPropertyValue(t, propertyName, xmlElement.SelectSingleNode(propertyName).InnerText);
255                 }
256                 list.Add(t);
257             }
258             return list;
259         }
260 
261         /// <summary>
262         /// 多条件查询 查询数组为空,表示查询所有
263         /// </summary>
264         /// <param name="pName">属性名</param>
265         /// <param name="value">属性值</param>
266         /// <param name="isEqual">true 等值查询,false 模糊查询</param>
267         /// <returns></returns>
268         public static List<T> GetListByCondition(String[] pNames, String[] values, Boolean isEqual)
269         {
270             List<T> list = new List<T>();
271             String className = typeof(T).Name;
272             XmlDocument xmldoc = new XmlDocument();
273             //加载xml文件
274             try
275             {
276                 xmldoc.Load(xmlPath + className + ".xml");
277             }
278             catch (Exception e)
279             {
280                 Console.WriteLine(e.Message);
281             }
282             // 拼接 XML XPath 查询字符串
283             String condition = GetXPath(pNames,values,isEqual);
284             String xPathStr = "Root/" + className + condition;
285 
286             // XPath 查询
287             XmlNodeList nodeList = xmldoc.SelectNodes(xPathStr);
288 
289             foreach (XmlNode xmlNode in nodeList)
290             {
291                 T t = Activator.CreateInstance<T>();
292                 XmlElement xmlElement = (XmlElement)xmlNode;
293                 // 属性遍历
294                 PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t);
295                 foreach (PropertyInfo propertyInfo in propertyInfos)
296                 {
297                     String propertyName = propertyInfo.Name;
298                     ReflectionUtils<T>.SetTPropertyValue(t, propertyName, xmlElement.SelectSingleNode(propertyName).InnerText);
299                 }
300                 list.Add(t);
301             }
302             return list;
303         }
304 
305 
306 
307         /// <summary>
308         /// 拼接 XPath 查询条件参数
309         /// 等值查询:String xPath = "users/user[username='huo' and password='123']";
310         /// 模糊查询:String xPath = "users/user[contains(username,'huo') and contains(password,'123')]";
311         /// </summary>
312         /// <param name="pNames"></param>
313         /// <param name="values"></param>
314         /// <returns></returns>
315         private static String GetXPath(String[] pNames, String[] values, Boolean isEqual)
316         {
317             StringBuilder sb = new StringBuilder();
318             //等值查询
319             if (isEqual)
320             {
321                 //添加第一个元素
322                 if (pNames.Length > 0)
323                 {
324                     sb.Append("[");
325                     sb.Append(pNames[0]);
326                     sb.Append("='");
327                     sb.Append(values[0]);
328                     sb.Append("'");
329                 }
330                 //添加后续元素
331                 if (pNames.Length > 1)
332                 {
333                     for (int i = 1; i < pNames.Length; i++)
334                     {
335                         sb.Append(" and ");
336                         sb.Append(pNames[i]);
337                         sb.Append("='");
338                         sb.Append(values[i]);
339                         sb.Append("'");
340                     }
341                 }
342                 //结尾加上 ]
343                 if (sb.Length > 0)
344                 {
345                     sb.Append("]");
346                 }
347             }
348             else   //模糊查询
349             {
350                 //添加第一个元素
351                 if (pNames.Length > 0)
352                 {
353                     sb.Append("[");
354                     sb.Append("contains(");
355                     sb.Append(pNames[0]);
356                     sb.Append(",'");
357                     sb.Append(values[0]);
358                     sb.Append("')");
359                 }
360                 //添加后续元素
361                 if (pNames.Length > 1)
362                 {
363                     for (int i = 1; i < pNames.Length; i++)
364                     {
365                         sb.Append(" and ");
366                         sb.Append("[");
367                         sb.Append("contains(");
368                         sb.Append(pNames[i]);
369                         sb.Append(",'");
370                         sb.Append(values[i]);
371                         sb.Append("')");
372                     }
373                 }
374                 //结尾加上 ]
375                 if (sb.Length > 0)
376                 {
377                     sb.Append("]");
378                 }
379             }
380             return sb.ToString();
381         }
382     }

 

posted @ 2010-10-28 15:14  taony  阅读(555)  评论(1)    收藏  举报