C# 自定义Section

时间:2022-03-14 16:38:30

一、在App.config中自定义Section,这个使用了SectionGroup

<?xml version="1.0" encoding="utf-8" ?>
<configuration> <configSections>
<sectionGroup name="IpTables">
<section name="IPs" type="Section.Test.MySectionHandler,Section.Test"/>
</sectionGroup>
</configSections> <IpTables>
<IPs>
<add key="ip" value="127.0.0.1"/>
<add key="port" value="8888"/> </IPs> </IpTables>
</configuration>

xml中的section 需要显示配置自定义的处理程序,即type属性
二、创建处理程序 MySectionHandler

  //实现 IConfigurationSectionHandler接口,并且读取自定义Section
public class MySectionHandler : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
var dic= new Dictionary<string, string>();
//可能会出现注释,所以需要显示过滤xml元素
foreach (XmlElement childNode in section.ChildNodes.OfType<XmlElement>())
{ dic.Add(childNode.Attributes["key"].InnerText,childNode.Attributes["value"].InnerText); }
return dic;
}
}

执行处理程序代码如下:

var dic= ConfigurationManager.GetSection("IpTables/IPs") as IDictionary<string,string>;

注意事项:

1.获取自定义Section,如果是SectionGroup,则需要 SectionGroup/Section 这种格式获取

2.一般该代码写在应用程序初始化处,只加载一次,然后将其值缓存至内存中即可使用

3.<configSections> 元素必须是 configuration 元素的第一个子元素

三、如何自定义比如log4net.config中那样的节点?

没难度,其实就是基本的xml操作了。