3. 自定义配置结构 (使用iconfigurationsectionhandler)
假设有以下的配置信息,其在myinfo可以重复许多次,那么应如何读取配置呢?这时就要使用自定义的配置程序了。
<myconfigs>
<myinfo area="fuzhou" device="printer" customer="muf" />
<myinfo area="shanghai" device="mobile" customer="liny" />
</myconfig>
访问代码如下:
hashtable cfgtable = (hashtable)configurationsettings.getconfig( "myconfigs" );
debug.assert( cfgtable.count == 2);
hashtable cfgfuzhou = (hashtable)cfgtable["fuzhou"];
hashtable cfgshanghai = (hashtable)cfgtable["shanghai"];
debug.assert( cfgfuzhou["device"] == "printer" );
debug.assert( cfgshanghai["device"] == "mobile" );
debug.assert( cfgfuzhou["customer"] == "muf" );
debug.assert( cfgshanghai["customer"] == "liny" );
foreach(hashtable cfg in cfgtable.values)
{
console.writeline("area={0} device={1} customer={2}", cfg["area"], cfg["device"], cfg["customer"]);
}
为了能使用上面的访问代码来访问配置结构,我们需要生成一个特定的配置读取类(configurationsectionhandler),例子很简单,就不多做说明了:
public class myinfosectionhandler: iconfigurationsectionhandler
{
public object create(object parent, object configcontext, system.xml.xmlnode section)
{
hashtable config = new hashtable();
foreach(xmlnode node in section.childnodes)
{
if(node.name != "myinfo")
throw new system.configuration.configurationexception("不可识别的配置项", node);
hashtable item = new hashtable();
foreach(xmlattribute attr in node.attributes)
{
switch(attr.name)
{
case "area":
case "device":
case "customer":
item.add(attr.name, attr.value);
break;
default:
throw new system.configuration.configurationexception("不可识别的配置属性", attr);
}
}
config.add(item["area"], item);
}
return config;
}
}
然后,我们再定义配置说明。其中,mynamespace.myinfosectionhandler 是myinfosectionhandler类的带名字空间的完整名称;myapp 则是定义myinfosectionhandler类的程序集不带扩展名的名字(如myapp.dll或myapp.exe):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!– 以下是自定义配置的声明 –>
<configsections>
<section name="myconfig" type="mynamespace.myinfosectionhandler, myapp" />
</configsections>
<myconfigs>
<myinfo area="fuzhou" device="printer" customer="muf" />
<myinfo area="shanghai" device="mobile" customer="liny" />
</myconfig>
</configuration>
根据上面的例子,我们可以使用iconfigurationsectionhandler来实现任意的配置文件结构。
(待续)