一、在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
1 //實作 IConfigurationSectionHandler接口,并且讀取自定義Section
2 public class MySectionHandler : IConfigurationSectionHandler
3 {
4 public object Create(object parent, object configContext, XmlNode section)
5 {
6 var dic= new Dictionary<string, string>();
7 //可能會出現注釋,是以需要顯示過濾xml元素
8 foreach (XmlElement childNode in section.ChildNodes.OfType<XmlElement>())
9 {
10
11 dic.Add(childNode.Attributes["key"].InnerText,childNode.Attributes["value"].InnerText);
12
13 }
14 return dic;
15 }
16 }
執行處理程式代碼如下:
var dic= ConfigurationManager.GetSection("IpTables/IPs") as IDictionary<string,string>;
注意事項:
1.擷取自定義Section,如果是SectionGroup,則需要 SectionGroup/Section 這種格式擷取
2.一般該代碼寫在應用程式初始化處,隻加載一次,然後将其值緩存至記憶體中即可使用
3.<configSections> 元素必須是 configuration 元素的第一個子元素。
三、如何自定義比如log4net.config中那樣的節點?
沒難度,其實就是基本的xml操作了。
轉載于:https://www.cnblogs.com/gaobing/p/6047746.html