轻量级的 XML ORM
开发中,经常使用xml来作数据库,涉及到对xml的操作比较频繁。如果每次都去一步步的写那些过程,真的是很浪费时间。经过一段时间的总结,我将xml的常用操作封装成一个dll,实现了对xml的增删改查。对一般的xml开发已经够用了。说是ORM其实也有些勉强,不过操作起来还是比较方便的。下面我将演示怎么利用XmlHelper这个dll,进行对xml的操作。
首先声明一个实体:
log.cs
using System;
using XmlHelper.Core;
public class Log:Entity
{
public string Title { get; set; }
public DateTime CreateTime { get; set; }
public string CategoryID { get; set; }
public string Content { get; set; }
public int ReadCounts { get; set; }
public int CommentCounts { get; set; }
}
接下来,我们将对这个实体进行一系列的操作:
1.增加一条数据,自动生成Log.xml保存在App_Data下。
public bool AddLog(string title, string content)
{
Log l = new Log();
l.CategoryID = "life" ;
l.CommentCounts = 0;
l.Content = content;
l.CreateTime = DateTime.Now;
l.ReadCounts = 0;
l.Title = title;
XmlDAO.AddToXml(l);
return true;
}
2.根据实体删除一条数据。
public bool DeleteLog(string id)
{
Log l = new Log();
l.ID = id;
XmlDAO.DeleteElement(l);
return true;
}
3.根据实体修改一条数据。
public bool UpdateLog(string id,string title, string content)
{
Log l = new Log();
l.ID=id;
l = (Log)XmlDAO.GetByID(l);
l.Content = content;
l.Title = title;
XmlDAO.UpdateAttribute(l);
return true;
}
4.得到所有实体,返回List。
public List<Log> GetAllLogs()
{
List<Log> lis = new List<Log>();
List<object> objects = XmlDAO.GetAll(new Log());
foreach (object obj in objects)
{
Log l = new Log();
l = (Log)obj;
lis.Add(l);
}
return lis;
}
5.根据xpath语法,查询xml,返回List.
public List<Log> GetByQuery(string query)
{
List<Log> lis = new List<Log>();
List<object> objects = XmlDAO.GetByQuery(new Log(),query);
foreach (object obj in objects)
{
Log l = new Log();
l = (Log)obj;
lis.Add(l);
}
return lis;
}
Log.xml 如下:
<?xml version="1.0" encoding="utf-8"?>
<root>
<Log Title="tttt1" CreateTime="2009-4-1 22:55:00" CategoryID="tec" Content="ttttt" ReadCounts="0" CommentCounts="0" ID="d606dcb8-5e04-4612-8faa-aa8494e47d2a" />
<Log Title="tttt2" CreateTime="2009-4-1 22:55:03" CategoryID="life" Content="ttttt" ReadCounts="0" CommentCounts="0" ID="edf546f8-0326-4707-858c-95436b58b901" />
</root>