zoukankan      html  css  js  c++  java
  • C# 自定义Section

    一、在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操作了。

  • 相关阅读:
    php中&符号什么意思
    lucene 笔记
    yslow详细解释
    sqlserver中如何实现时间按月,日,小时分组查询
    用Lucene.net对数据库建立索引及搜索2
    lucene.net索引文件存储简析
    C #中的几个线程同步对象方法 1
    lucene 全文检索简介
    判断jquery对象是否可见
    Lucene.net多字段(Fields)、多索引目录(IndexSearcher)搜索
  • 原文地址:https://www.cnblogs.com/gaobing/p/6047746.html
Copyright © 2011-2022 走看看