网上借鉴了一部分、不全、有的方法没有给出、自己瞎补的、反正能用!
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Reflection; using System.Windows.Forms; namespace BaiDuRankCollection { // XmlUtils<User>.UpdateXmlItem(User); //XmlUtils<User>.DeleteXMLItem(User); //List<User> users= XmlUtils<User>.GetList(); //List<User> users= XmlUtils<User>.GetListByCondition(new String[] {},new String[] {},true); //List<User> users= XmlUtils<User>.GetListByCondition(new String[] { "Name" },new String[] { "测" },false); //List<User> users= XmlUtils<User>.GetListByCondition(new String[] { "Name","Id" },new String[] { "测试","1" },true); /// <summary> /// 通用的 XML 操作类 (微型本地xml数据库) /// </summary> /// <typeparam name="T"></typeparam> public class XmlUtils<T> { /// <summary> /// xml 保存路径 /// </summary> private static readonly string xmlPath = Application.StartupPath + @"\XmlMOdel\"; /// <summary> /// 主键名 /// </summary> public static readonly string primaryPropertyName = "Id"; /// <summary> /// 创建XML文件 /// </summary> /// <param name="t"></param> public static void CreateXMLFile(T t) { string className = ReflectionUtils<T>.GetClassName(t); XmlDocument xmldoc = new XmlDocument(); //加入XML的声明段落 XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"",""); xmlnode.Value = "version=\"1.0\" encoding=\"utf-8\""; xmldoc.AppendChild(xmlnode); //加入一个根元素 XmlElement xmlelem = xmldoc.CreateElement("Root"); //XmlText xmltext = xmldoc.CreateTextNode ( "Root Text" ) ; //xmlelem.AppendChild ( xmltext ) ; xmldoc.AppendChild(xmlelem); if (!Directory.Exists(xmlPath)) { Directory.CreateDirectory(xmlPath); } xmldoc.Save(xmlPath + className + ".xml"); } /// <summary> /// 判断主键是否唯一 /// </summary> /// <param name="xmldoc"></param> /// <param name="className"></param> /// <param name="o"></param> /// <returns></returns> private static Boolean IsPrimaryKeyUnique(XmlDocument xmldoc,string className,Object o) { string xPathStr = "Root/" + className + "[" + primaryPropertyName + "='" + o.ToString() + "']"; // XPath 查询 XmlNodeList nodeList = xmldoc.SelectNodes(xPathStr); if (nodeList.Count > 0) { return false; } else { return true; } } /// <summary> /// 插入对象 /// </summary> /// <param name="t"></param> public static void InsertXmlItem(T t) { string className = ReflectionUtils<T>.GetClassName(t); //if (!Directory.Exists(xmlPath + className + ".xml")) //{ // CreateXMLFile(t); //} XmlDocument xmldoc = new XmlDocument(); //加载xml文件 try { xmldoc.Load(xmlPath + className + ".xml"); } catch (Exception e) { Console.WriteLine(e.Message); } //判断 主键号是否有值 或者 主键已经存在 //Object o = ReflectionUtils<T>.GetTPropertyValue(t,primaryPropertyName); //if (o != null && IsPrimaryKeyUnique(xmldoc,className,o)) //{ //获取根节点 XmlNode root = xmldoc.DocumentElement; //创建子节点 XmlElement itemNode = xmldoc.CreateElement(className); PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t); foreach (PropertyInfo propertyInfo in propertyInfos) { string propertyName = propertyInfo.Name; string propertyValue = propertyInfo.GetValue(t,null) == null ? "" : propertyInfo.GetValue(t,null).ToString(); XmlElement propertyNode = xmldoc.CreateElement(propertyName); propertyNode.InnerText = propertyValue; itemNode.AppendChild(propertyNode); } root.AppendChild(itemNode); xmldoc.Save(xmlPath + className + ".xml"); //} //else //{ // throw new Exception("插入数据失败,插入的主键为空或者主键已经存在。"); //} } /// <summary> /// 批量插入对象 /// </summary> /// <param name="list"></param> public static void BatchInsertXmlItem(List<T> list) { string className = typeof(T).Name; XmlDocument xmldoc = new XmlDocument(); //加载xml文件 try { xmldoc.Load(xmlPath + className + ".xml"); } catch (Exception e) { Console.WriteLine(e.Message); } //获取根节点 XmlNode root = xmldoc.DocumentElement; foreach (T t in list) { //创建子节点 XmlElement itemNode = xmldoc.CreateElement(className); PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t); foreach (PropertyInfo propertyInfo in propertyInfos) { string propertyName = propertyInfo.Name; string propertyValue = propertyInfo.GetValue(t,null).ToString(); XmlElement propertyNode = xmldoc.CreateElement(propertyName); propertyNode.InnerText = propertyValue; itemNode.AppendChild(propertyNode); } root.AppendChild(itemNode); } xmldoc.Save(xmlPath + className + ".xml"); } /// <summary> /// 更新对象 /// </summary> /// <param name="t"></param> public static void UpdateXmlItem(T t) { string className = ReflectionUtils<T>.GetClassName(t); XmlDocument xmldoc = new XmlDocument(); //加载xml文件 try { xmldoc.Load(xmlPath + className + ".xml"); } catch (Exception e) { Console.WriteLine(e.Message); } // 拼接 XML XPath 查询字符串 string xPathStr = "Root/" + className + "[" + primaryPropertyName + "='" + ReflectionUtils<T>.GetTPropertyValue(t,primaryPropertyName) + "']"; // XPath 查询 XmlNodeList nodes = xmldoc.SelectNodes(xPathStr); if (nodes.Count > 0) { foreach (XmlNode xmlNode in nodes) { XmlElement xmlElement = (XmlElement)xmlNode; // 属性遍历 PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t); foreach (PropertyInfo propertyInfo in propertyInfos) { string propertyName = propertyInfo.Name; string propertyValue = propertyInfo.GetValue(t,null).ToString(); // 更新 xmlElement.SelectSingleNode(propertyName).InnerText = propertyValue; } } // 保存 xmldoc.Save(xmlPath + className + ".xml"); } } /// <summary> /// 删除对象 /// </summary> /// <param name="t"></param> public static void DeleteXMLItem(T t) { string className = ReflectionUtils<T>.GetClassName(t); XmlDocument xmldoc = new XmlDocument(); //加载xml文件 try { xmldoc.Load(xmlPath + className + ".xml"); } catch (Exception e) { Console.WriteLine(e.Message); } // 拼接 XML XPath 查询字符串 string xPathStr = "Root/" + className + "[" + primaryPropertyName + "='" + ReflectionUtils<T>.GetTPropertyValue(t,primaryPropertyName) + "']"; // XPath 查询 XmlNodeList nodes = xmldoc.SelectNodes(xPathStr); if (nodes.Count > 0) { foreach (XmlNode xmlNode in nodes) { xmlNode.ParentNode.RemoveChild(xmlNode); } xmldoc.Save(xmlPath + className + ".xml"); } } /// <summary> /// 获取所有对象 /// </summary> /// <returns></returns> public static List<T> GetList() { List<T> list = new List<T>(); string className = typeof(T).Name; XmlDocument xmldoc = new XmlDocument(); //加载xml文件 try { xmldoc.Load(xmlPath + className + ".xml"); } catch (Exception e) { Console.WriteLine(e.Message); } XmlNodeList nodeList = xmldoc.GetElementsByTagName(className); foreach (XmlNode xmlNode in nodeList) { T t = Activator.CreateInstance<T>(); XmlElement xmlElement = (XmlElement)xmlNode; // 属性遍历 PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t); foreach (PropertyInfo propertyInfo in propertyInfos) { string propertyName = propertyInfo.Name; object nodeString= xmlElement.SelectSingleNode(propertyName).InnerText; ReflectionUtils<T>.SetTPropertyValue(t,propertyName,nodeString); } list.Add(t); } return list; } /// <summary> /// 多条件查询 查询数组为空,表示查询所有 /// </summary> /// <param name="pName">属性名</param> /// <param name="value">属性值</param> /// <param name="isEqual">true 等值查询,false 模糊查询</param> /// <returns></returns> public static List<T> GetListByCondition(string[] pNames,string[] values,Boolean isEqual) { List<T> list = new List<T>(); string className = typeof(T).Name; XmlDocument xmldoc = new XmlDocument(); //加载xml文件 try { xmldoc.Load(xmlPath + className + ".xml"); } catch (Exception e) { Console.WriteLine(e.Message); } // 拼接 XML XPath 查询字符串 string condition = GetXPath(pNames,values,isEqual); string xPathStr = "Root/" + className + condition; // XPath 查询 XmlNodeList nodeList = xmldoc.SelectNodes(xPathStr); foreach (XmlNode xmlNode in nodeList) { T t = Activator.CreateInstance<T>(); XmlElement xmlElement = (XmlElement)xmlNode; // 属性遍历 PropertyInfo[] propertyInfos = ReflectionUtils<T>.GetPropertyInfos(t); foreach (PropertyInfo propertyInfo in propertyInfos) { string propertyName = propertyInfo.Name; ReflectionUtils<T>.SetTPropertyValue(t,xmlElement.SelectSingleNode(propertyName).InnerText); } list.Add(t); } return list; } /// <summary> /// 拼接 XPath 查询条件参数 /// 等值查询:string xPath = "users/user[username='huo' and password='123']"; /// 模糊查询:string xPath = "users/user[contains(username,'huo') and contains(password,'123')]"; /// </summary> /// <param name="pNames"></param> /// <param name="values"></param> /// <returns></returns> private static string GetXPath(string[] pNames,Boolean isEqual) { StringBuilder sb = new StringBuilder(); //等值查询 if (isEqual) { //添加第一个元素 if (pNames.Length > 0) { sb.Append("["); sb.Append(pNames[0]); sb.Append("='"); sb.Append(values[0]); sb.Append("'"); } //添加后续元素 if (pNames.Length > 1) { for (int i = 1; i < pNames.Length; i++) { sb.Append(" and "); sb.Append(pNames[i]); sb.Append("='"); sb.Append(values[i]); sb.Append("'"); } } //结尾加上 ] if (sb.Length > 0) { sb.Append("]"); } } else //模糊查询 { //添加第一个元素 if (pNames.Length > 0) { sb.Append("["); sb.Append("contains("); sb.Append(pNames[0]); sb.Append(",'"); sb.Append(values[0]); sb.Append("')"); } //添加后续元素 if (pNames.Length > 1) { for (int i = 1; i < pNames.Length; i++) { sb.Append(" and "); sb.Append("["); sb.Append("contains("); sb.Append(pNames[i]); sb.Append(",'"); sb.Append(values[i]); sb.Append("')"); } } //结尾加上 ] if (sb.Length > 0) { sb.Append("]"); } } return sb.ToString(); } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。