您的位置:首页 > 其它

基于XML的配置文件访问接口设计和实现

2005-02-18 02:24 861 查看
基于XML的配置文件访问接口设计和实现(1)

目录
摘要
配置文件结构
XmlConfigReader类的实现
XmlConfigReader类的使用

摘要
在进行程序开发过程中,经常要将一些程序设置/使用的信息储存起来.由于这些信息和程序的设置/使用相关,与程序有相当的独立性,所以不可能硬编码到程序中.在这个时候我们选择使用基于Xml的配置文件进行存储.Microsoft的.NET Framework提供了一系列的基于.Config文件的读取的类,如System.Configuration 命名空间提供的AppSettings等类.但是此命名空间提供的类只能对配置文件进行读取,不能进行设置.所以在这里,我们实现自己的一个基于Xml的配置文件的类XmlConfigReader/XmlConfigWriter.

配置文件的结构
为了达到与原有的,系统自带的(.Config)配置文件的兼容性,我们选择使用类似.Config 文件的结构.示例如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="TimeOut" value="5000"/>
<add key="UserName" value="client7" />
<add key="FileServerPort" value="8050" />
<add key="SpliteCharsForCMD" value=":"/>
<add key="SpliteCharsForItem" value=";"/>
<add key="SpliteCharsForSubItem" value=","/>
</appSettings>
<SockBaseSettings>
<addd key="ServerIP" value="localhost"/>
</SockBaseSettings>
</configuration>
所有的要设置的信息都放在Configuration节点的子节点(如appSettings/SockBaseSettings)的子节点中,这种结构有助于将不同的设置的信息进行归类/统一.结构和系统的.Config结构基本类似.这样就可以很方便的将此自定义的结构转为.Config文件.

XmlConfigReader类的实现
现在文件的基本结构已完成了,现在就开始编码,完成XmlConfigReader.
由于配置文件是以文件的形式放在硬盘上面的,所以这个XmlConfigReader类在解析Xml文件前得得到文件的路径.
public class XmlConfigReader
{
private string _filepath;

public XmlConfigReader(string filepath){
_filepath = Path.GetFullPath(filepath).ToUpper();
}
}
好,现在可以得到文件路径了.然后就是对配置文件进行解析了.在这里,我们选用.NET Framework提供的System.Xml命名空间中的轻量级的XmlTextReader来对配置文件进行解析.对应的XmlConfigReader中的函数定义如下:
public string Process(string sectionName,string key){
bool inConfiguration = false;
bool inSection = false;
string values;
XmlTextReader reader = new XmlTextReader(_filepath);
while( reader.Read()){
if( reader.IsStartElement()){
if( reader.Prefix == String.Empty)
{
if( reader.LocalName == "configuration")
{
inConfiguration = true;
}
else if( inConfiguration == true){
if( reader.LocalName == sectionName){
inSection = true;
}
else if( inSection && reader.LocalName == "add"){
if( reader.GetAttribute("key") == null || reader.GetAttribute("value") == null)
{
throw new Exception(sectionName + " key or value is null");
}
if( reader.GetAttribute("key") == key){
values = reader.GetAttribute("value");
break;
}
}
}
}
}
}
reader.Close();
return values;
}
通过XmlTextReader的Read()函数对Xml文件中的节点进行遍历.同时先判断是否属于configuration节点中,再判断是否属于相应的sectionName中.只有在这两部分同时成立的时候才判断是否是相应的Key.如果是,得到其Value,并返回.

XmlConfigReader类的使用
好了,现在通过XmlConfigReader可以对配置文件进行读取了,这里我们看看实际使用的代码:
public class TestXmlConfigReader{
public void GetValues(){
XmlConfigReader reader = new XmlConfigReader(@"AppConfig.xml");
String Temp;
// Get appSettings username value
Temp = reader.Process("appSettings",”UserName");
// Get SockBaseSettings ServerIP value
Temp = Reader.Process(“SockBaseSettings”,”ServerIP”);
}
}

总结
通过XmlConfigReader类,我们可以很方便的自定义我们自己的配置文件.

基于XML的配置文件访问接口设计和实现(2)

目录
摘要
XmlConfigWriter类的实现
XmlConfigWriter类的使用

摘要
在进行程序开发过程中,经常要将一些程序设置/使用的信息储存起来.由于这些信息和程序的设置/使用相关,与程序有相当的独立性,所以不可能硬编码到程序中.在这个时候我们选择使用基于Xml的配置文件进行存储.Microsoft的.NET Framework提供了一系列的基于.Config文件的读取的类,如System.Configuration 命名空间提供的AppSettings等类.但是此命名空间提供的类只能对配置文件进行读取,不能进行设置.所以在这里,我们实现自己的一个基于Xml的配置文件的类XmlConfigReader/XmlConfigWriter.

XmlConfigWriter类的实现
由于要对配置文件进行写入,而且可能写入的次数比较多.所以这里我们不使用轻便的XmlTextWriter,使用XmlDocument.XmlDocument可以在内存中修改所有的Xml的节点,只有等到显式的调用Save函数的时候才会保存Xml文件.在有大量修改的时候,性能要好一些.
同样的,先实现XmlConfigWriter的构造函数
public class XmlConfigWriter
{
private string _filepath;
private XmlDocument doc ;
public XmlConfigWriter(string filepath)
{
_filepath = Path.GetFullPath(filepath);
doc =new XmlDocument();
doc.Load(_filepath);
}
}
通过构造函数,将配置文件的路径传进去,同时调用XmlDocument的Load方法,将此文件加载到内存中.
这里我们使用的是XmlDocument类.它实现 W3C 文档对象模型 (DOM) 级别 1 核心 (Level 1 Core) 和核心 DOM 级别 2 (Core DOM Level 2)。DOM 是 XML 文档的内存中(缓存)树状表示形式,允许对该文档的导航和编辑.通过XmlDocument,我们就可以很方便的在内存中直接操作节点.
.对配置文件的写入,不外忽三种,一种就是新插入一个节点,一种就是对现有节点的修改,最后一个就是删除现有的节点.我们首先从插入开始入手.代码如下:
private XmlNode CreateXmlNode(string localname){
return doc.CreateNode(XmlNodeType.Element,localname,"");
}

private XmlAttribute CreateXmlAttribute(string localname){
return doc.CreateAttribute("",localname,"");
}
public void AddSection(string section){
XmlNode secNode = doc.SelectSingleNode("/configuration/"+section);
if(secNode != null){
return;
}
doc.DocumentElement.AppendChild(CreateNode(section));
}

public void AddKey(string section,string key,string value){
XmlNode secNode = doc.SelectSingleNode("/configuration/"+section);
if( doc.SelectSingleNode("/configuration/" + section + "/add[@key=/"" + key + "/"]") != null)
{
return;
}
XmlNode chi = CreateXmlNode("add");
XmlAttribute att = CreateXmlAttribute("key");
att.Value = key;
chi.Attributes.Append(att);
att = CreateXmlAttribute("value");
att.Value = value;
chi.Attributes.Append(att);
secNode.AppendChild(chi);
}
对于配置文件的插入,有两种情况,一个就是插入一个新的Section节点(即appSettings/SockBaseSettings这样的节点),一个就是在当前的Section节点下面插入一个新的add节点.在上面的代码中,对于插入节点的操作,都是首先通过doc的SelectSingleNode函数来判断是否已存在此同名节点,如果存在,则直接return,避免创建同名的节点.但是,由于在最终使用的add节点是分属于不同的Section节点的,所以只是判断在同一个Section节点下面的此节点不能同名.
如果不存在同名的节点,就通过secNode.AppentChild函数将此新建的(通过CreateXmlNode函数)节点加入到doc对象中.同时,对于add节点,通过CreateXmlAttribute函数及XmNode.Attributes.Appent函数将其key / value属性加入到此节点中.这样,插入操作就完成了.
接着我们来完成删除操作.删除操作直接通过XmlDocument的SelectSingleNode得到目标节点的父节点,再通过XmlNode.RemoveChild操作将其删除.代码如下:
public void DeleteSection(string section){
XmlNode secNode = doc.SelectSingleNode("/configuration/"+section);
doc.DocumentElement.RemoveChild(secNode);
}

public void DeleteKey(string section,string key){
XmlNode secNode = doc.SelectSingleNode("/configuration/" + section + "/add[@key=/"" + key + "/"]");
if(secNode != null)
{
secNode.ParentNode.RemoveChild(secNode);
}
}

现在开始修改操作.对于修改操作,思路是这样的,首先通过XmlDocument的SelectSingleNode搜索,看是否有满足条件的节点.如果没有,直接return,如果存在,则分两情况.对于add节点,只是直接修改其value属性.对于Section节点,则是通过遍历把其下所有的子节点(add节点)得到,再把此Section节点删除,再生成一个新的节点(这个新的节点的Name就为要设置的值),再把得到的所有子节点再赋给这个新的节点.代码如下:
public void ModifySection(string oldSection,string newSection){
XmlNode secNode = doc.SelectSingleNode("/configuration/"+oldSection);
XmlNodeList list = secNode.ChildNodes;
doc.DocumentElement.RemoveChild(secNode);
secNode = doc.CreateNode(XmlNodeType.Element,newSection,"");
foreach( XmlNode i in list){
secNode.AppendChild(i);
}
doc.DocumentElement.AppendChild(secNode);
}

public void ModifyKey(string section,string key,string value){
XmlNode secNode = doc.SelectSingleNode("/configuration/" + section + "/add[@key=/"" + key + "/"]");
if(secNode != null)
{
secNode.Attributes["value"].Value = value;
}
}
好了,插入,修改,删除操作到现在基本完成了,但是现在还只是在内存中进行操作,还不是对实际的文件进行操作.这个时候,我们就还得通过XmlDocument.Save函数把内存中修改好的Xml文件写入到文件中去.代码如下:
public void Save(){
doc.Save(_filepath);
}
public void Save(string filepath)
{
doc.Save(filepath);
}

XmlConfigWriter类的使用
使用方法很简单.先产生一个XmlConfigWriter对象,通过构造函数把配置文件传进去,再通过Add/Modify/Delete等函数进行操作.代码如下:
XmlConfigWriter Writer = new XmlConfigWriter(@”appconfig.xml”);
Writer.AddSection(“appSettings”);
Writer.AddKey(“appSettings”,”ServerIP”,”localhost”);
Writer.ModifyKey(“appSettings”,”ServerIP”,”127.0.0.1”);
Writer.ModifySection(“appSettings”,”SockBaseSettings”);
Writer.DeleteKey(“SockBaseSettings”,”ServerIP”);
Writer.DeleteSection(“SockBaseSettings”);
Writer.Save();

总结
通过编写XmlConfigWriter,我们学会使用XmlDocument的使用.

基于XML的配置文件访问接口设计和实现(3)

目录
摘要
增加缓存支持
增加配置文件监视
增加ConfigurationSettings类

摘要
前面的两篇中,我们实现了XmlConfigReader和XmlConfigWriter的基本功能.由于XmlConfigReader的实现方式是每请求一次,就去解析配置文件一次,性能很低下.同时,为了更方便使用,我们增加一个ConfigurationSettings类,用来调用XmlConfigReader和XmlConfigWriter,使之用起来和System.Configuration中的类使用方式一样.

增加缓存支持
由于XmlConfigReader的实现方式是请求一次,解析配置文件一次,而且配置文件的信息在程序运行的时会大量使用,这样子显然效率太低.因此,这里就要使用到缓存.
缓存,其实就相当于一个静态的变量,在整个程序运行时是唯一的,通过这样的一个变量,把信息存储到这个变量里面,在程序的其它地方就可以直接得到这个信息了.从而避免了频繁的解析配置文件.这里,我们选择使用Hashtable做为缓存变量.
在MSDN中,我们可以查到System.Configuration命名空间中的AppSettings类返回的是一个NameValueCollection(Key/Value键值对).为了方便使用,我们将配置文件解析后的信息也存成NameValueCollection这样的集合.
这样定义好了后,对于Hashtable中的Key设置为Section节点的名字(appSettings/SockBaseSettings),其Value值即为此节点的所有子节点的NameValueCollection类的对象.
修改代码.给XmlConfigReader增加一个静态Hashtable变量,并修改相关函数.把得到的信息直接以NameValueCollection的形式存入到此Hashtable中.
private static Hashtable confTypes = new Hashtable();
private string rootname;

public void Process(){
XmlTextReader reader = new XmlTextReader(_filepath);
while( reader.Read()){
if( reader.IsStartElement()){
#region Analyze the files
if( reader.Prefix == String.Empty)
{

if( reader.LocalName == "configuration")
{
inConfiguration = true;
}
else if( inConfiguration == true){

if(reader.LocalName == "add")
{
if( reader.GetAttribute("key") == null || reader.GetAttribute("value") == null)
{
throw new Exception(rootname + " key or value is null");
}
AddKey(tables,reader.GetAttribute("key"),reader.GetAttribute("value"));
}
else
{
rootname = reader.LocalName;
}
}
}
#endregion
}
else if ( reader.LocalName == "configuration"){
inConfiguration = false;
}
}
reader.Close();
}

private void AddKey(string key,string value){
NameValueCollection collection ;
if(confTypes.ContainsKey( rootname )){
collection = (NameValueCollection) confTypes [rootname];
}
else{
lock(confTypes.SyncRoot){
collection = new NameValueCollection();
confTypes.Add( rootname,collection);
}
}

collection.Add(key,value);
}
上面代码中,我们修改了Process函数.把原来的直接return结果的地方改成调用AddKey函数.通过一个类成员 rootname临时储存当前的SectionName,通过AddKey把得到的Key/Value加入到Hashtable中.
现在这样修改后,就不能直接通过Process得到我们想到得到的Key的Value了.所以我们再写一个函数,
public NameValueCollection GetCollection(string SectionName){
if( confTypes.ContainsKey(SectionName)){
return (NameValueCollection)confTypes[SectionName];
}
else{
throw new Exception(confName + " is not found in XmlConfiguration files");
}
}
这里,我们直接通过SectionName得到此节点所有的子节点的NameValueCollection集合.这样,我们就可以得到我们想要的值了.

增加配置文件监视
上面的代码实现了配置文件的缓存.大大提高了灵活性.但是存在一个问题,就是,如果配置文件修改了,这个缓存不会自动更新.
要解决这个问题,我们得使用FileSystemWatcher这个类,用来订阅文件修改消息,进而更新缓存.由于在第一次解析前就要把此配置文件加入到监视文件表中,所以我们修改XmlConfigReader,增加一个静态的FileSystemWatcher,用来保存监视文件的对象,增加一个静态的Bool值表明是否修改过.再修改构造函数,使配置文件在一开始就加入到监视列表中.代码如下:
Private static FileSystemWatcher watch = new FileSystemWatcher();
Private static bool isModify = true;
public XmlConfigReader(string filepath){
_filepath = Path.GetFullPath(filepath).ToUpper();
watch.IncludeSubdirectories = false;
watch.Path = Path.GetDirectoryName(filepath);
watch.NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite;
watch.Filter = Path.GetFileName(filepath);
watch.Changed += new FileSystemEventHandler(Change_Even);
watch.EnableRaisingEvents = true;
}
由于是通过事件机制实现文件修改通知的,所以我们还要实现Chane_Even这个函数,通过这个函数修改isModify的值.
private void Change_Even(object sender, FileSystemEventArgs e){
isModify = true;
}
这样子,对于配置文件的监视的代码就完成了,现在就是修改我们的GetCollection代码的时候了.
修改后的代码如下:
public NameValueCollection GetCollection(string SectionName){
if( isModify ){
lock(confTypes.SyncRoot){
confTypes.Clear();
Process();
}
isModify = false;
}
if( confTypes.ContainsKey(SectionName)){
return (NameValueCollection)confTypes[SectionName];
}
else{
throw new Exception(confName + " is not found in XmlConfiguration files");
}
}
到现在,整个XmlConfigReader的代码已完成了,可以实现对文件的监视,从而动态修改缓存中的值.

增加ConfigurationSettings类
为了便于使用,我们增加了一个ConfigurationSettings的类,使用他的用法和System.Configuration命名空间中的类的用法一样.代码定义如下:
public class ConfigurationSettings : XmlConfigWriter
{
private static string _filepath = @"AppConfig.xml";
public static string DefaultFilePath
private static XmlConfigReader reader;
{
get{return _filepath;}
set{_filepath = Path.GetFullPath(value);}
}

public static NameValueCollection AppSettings
{
get{
if( reader == null){
reader = new XmlConfigReader(DefaultFilePath);
}
return reader.GetCollection("appSettings");
}
}

public static NameValueCollection GetConfig(string sectionName){
get{
if( reader == null){
reader = new XmlConfigReader(DefaultFilePath);
}
return reader.GetCollection(sectionName);
}
}
这样,使用起来就和系统自带的一样了.

总结
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: