在.net中,因为对不同的节点,都对应着类去对它进行处理,。net里面为了方便,已经内置了一些类供我们使用,使我们在读取配置文件时,不必自己去定义类去处理自己定义的自定义节点。
下面我们写了这样一个配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!--使用IgnoreSection处理自定义节点-->
<!--<section name="mailServeraddress" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false " restartOnExternalChanges="true"/>-->
<section name="mailServeraddress" type="System.Configuration.SingleTagSectionHandler" />
<!--注意,指定处理程序的配置文件要写在自定义配置文件的前面-->
</configSections>
<mailServeraddress address="mail.tracefact.net" username="lhc" password="124324"/>
</configuration>
节点名称为:mailServeraddress,有三个属性,在section里定义了SingleTagSectionHandler来处理这个节点。
namespace 自定义节点和内置处理程序
{
class Program
{
static void Main(string[] args)
{
ExampleSingleTagSectionHandler();
}
private static void ExampleSingleTagSectionHandler() {
//SingleTagSectionHandler会以hashtable的形式返回节点的所有属性
Hashtable mailServer = (Hashtable)ConfigurationManager.GetSection("mailServeraddress");//调用GetSection会返回一个hashtable
string address = mailServer["address"].ToString();
string username = mailServer["username"].ToString();
string passWord = mailServer["password"].ToString();
Console.WriteLine(address+"----"+username+"------"+passWord);
}
}
}
配置文件写好后,调用GetSection强转hashtable后,就可以用key——value的形式读取节点的属性值了。
在.net中,除了上面例子中的这个type,我们也可以使用其它内置type来处理自定义节点。