除了使用继承IConfigurationSectionHandler的方法定义处理自定义节点的类,还可以通过继承ConfigurationSection类实现同样效果。
首先说下.Net配置文件中一个潜规则
在配置节点时,对于想要进行存储的参数数据,可以采用两种方式:一种是存储到节点的属性中,另一种是存储在节点的文本中。
因为一个节点可以有很多属性,但是只要一个innertext,而要在程序中将这两种形式区分开会带来复杂性。 为了避免这个问题,.net的配置文件只是用属性存储而不使用innertext.
接着,我们来写一个符合这个潜规则的自定义配置文件,方便测试:
<mailServerGroup provider="www.baidu.com"> <mailServers> <mailServer client="http://blog.gaodaima.com/lhc1105" address="[email protected]" userName="lhc" password="2343254"/> <mailServer client="http://blog345.gaodaima.com/lhc1105" address="[email protected]" userName="dfshs水田如雅" password="2334t243的萨芬234254"/> <mailServer client="http://blog436.gaodaima.com/lhc1105" address="[email protected]" userName="sdfhdfs水田如雅" password="23ewrty2343的萨芬234254"/> <mailServer client="http://blo345734g.gaodaima.com/lhc1105" address="[email protected]" userName="sdfher水田如雅" password="23erwt43的萨芬234254"/> </mailServers> </mailServerGroup>
接着,我们来写相应的处理类,这里我们由内向外来写:
首先是最内层的mailServer:
/// <summary> /// Class MailServerElement:用于映射mailServer节点,这里是实际存储数据的地方; /// </summary> /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:51:57</remarks> public sealed class MailServerElement : ConfigurationElement //配置文件中的配置元素 { /// <summary> /// Gets or sets the client. /// </summary> /// <value>The client.</value> /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:40</remarks> [ConfigurationProperty("c<div style="color:transparent">本文来源gaodai.ma#com搞##代!^码@网*</div>lient", IsKey = true, IsRequired = true)] //client是必须的key属性,有点儿主键的意思,例如,如果定义多个client相同的节点,循环读取的话就只读取到最后一个值 public string Client { get { return this["client"] as string; } set { this["client"] = value; } } /// <summary> /// Gets or sets the address. /// </summary> /// <value>The address.</value> /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:38</remarks> [ConfigurationProperty("address")] public string Address { get { return this["address"] as string; } set { this["address"] = value; } } /// <summary> /// Gets or sets the name of the user. /// </summary> /// <value>The name of the user.</value> /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:35</remarks> [ConfigurationProperty("userName")] public string UserName { get { return this["userName"] as string; } set { this["userName"] = value; } } /// <summary> /// Gets or sets the password. /// </summary> /// <value>The password.</value> /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:33</remarks> [ConfigurationProperty("password")] public string Password { get { return this["password"] as string; } set { this["password"] = value; } } }