通用XML操作类(微型本地xml数据库)

View Code
使用的时候,只要先建立对象模型,把模型做为参数传递进去即可,非常方便。



XmlUtils<User>.CreateXMLFile(new User());
XmlUtils<User>.InsertXmlItem(User);
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);

    //author:俞立全
//Email:<a href="mailto:vv_2048@163.com">vv_2048@163.com
</a> //Date: 2010-10-24
/// <summary>
/// 通用的 XML 操作类 (微型本地xml数据库)
/// </summary>
/// <typeparam name="T"></typeparam>
class XmlUtils<T>
{
/// <summary>
/// xml 保存路径
/// </summary>
private static readonly String xmlPath = @"data\";
/// <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);
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) == 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");
}

/// <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) == null ? "" : 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;
ReflectionUtils<T>.SetTPropertyValue(t, propertyName, xmlElement.SelectSingleNode(propertyName).InnerText);
}
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, propertyName, 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, String[] values, 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();
}
}
原文地址:https://www.cnblogs.com/Mr0909/p/2290538.html