一个C#的XML数据库访问类

原文地址:http://hankjin.blog.163.com/blog/static/33731937200942915452244/

程序中不可避免的要用到配置文件或数据,对于数据量比较小的程序,部署数据库花费的时间就显得浪费了,因此用XML来存储不妨为一个很好的办法,而且结合C#的DataSet,我们可以很轻易的封装出一个代码简单而功能强大的数据访问类XMLConfig
config.xml
<root>
 
<table1>
    <rowName1>hello</rowName1>
   
<rowName2>World</rowName2>
  </table1>
 
<table1>
    <rowName1>hank</rowName1>
   
<rowName2>Joke</rowName2><!--table1, row1:
ds.Tables["table1"].Rows[1]["rowName2"] -->
  </table1>

 
<table2>
  </table2>
  <table2>
 
</table2>

  <table3>
 
</table3>
</root>

    class XMLConfig
    {
       
/// <summary>
        /// XML文件名
        ///
</summary>
        private static string fileName;
        ///
<summary>
        /// 数据集
        /// </summary>
       
private static DataSet objDataSet;
        /// <summary>
        ///
表名
        /// </summary>
        private string
tableName;
        private bool updated = false;
        static
XMLConfig()
        {
            fileName =
"data//config.xml";
            objDataSet = new DataSet();
           
objDataSet.ReadXml(fileName);
        }
        ///
<summary>
        /// 获取一个表
        /// </summary>
       
/// <param name="tableName">表名</param>
        public
XMLConfig(string tableName)
        {
            this.tableName =
tableName;
        }
        /// <summary>
        ///
获取配置
        /// </summary>
        /// <param
name="index"></param>
        /// <param
name="row"></param>
        ///
<returns></returns>
        public object GetConfig(int index,
string row)
        {
            return
objDataSet.Tables[tableName].Rows[index][row];
        }
        ///
<summary>
        /// 修改配置
        /// </summary>
       
/// <param name="index"></param>
        /// <param
name="row"></param>
        /// <param
name="value"></param>
        public void SetConfig(int index,
string row, string value)
        {
           
objDataSet.Tables[tableName].Rows[index][row] = value;
            updated =
true;
        }
        /// <summary>
        ///
析构函数,程序退出时,如果有修改,则把修改写回XML文件中
        /// </summary>
       
~XMLConfig()
        {
            if(updated)
               
objDataSet.WriteXml(fileName);
        }
    }

posted @ 2014-04-30 09:51  CocoWang  阅读(509)  评论(0编辑  收藏  举报