zoukankan      html  css  js  c++  java
  • 小小的储备知识:有关于读取section 节点的数据

    在实际项目中,我们喜欢将一些容易改变的东西写在配置文件中(比如数据链接字符串、比如Ioc的注册等等)

    那么怎样读取我们写入配置文件的值,以及怎样对配置文件的值进行处理呢?

    下面主要介绍这个功能

    链接字符串的读取没有任何新意,直接传统读取方法即可,

    之后我们也可以自定义节点进行读取,方法如下

    首先需要在configuration.configSections 下注册节点使用的程序

    <configSections>
        <sectionGroup name="TestSectionGroup">
            <section name="TestSection" type="SSHConsole.TestHandler,SSHConsole"/>
        </sectionGroup>
    </configSections>

    此处SectionGroup 为父节点,主要用来做容器(接纳子节点),同时定义一个节点TestSection,之后指出调用此节点的时候,使用SSHConsole.TestHandler 这个对象进行解析,之后这个对象存在于SSHConsole 这个assembly中。

    之后我们就可以配置自己的节点了,我做了个简单的配置

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
            <sectionGroup name="TestSectionGroup">
                <section name="TestSection" type="SSHConsole.TestHandler,SSHConsole"/>
            </sectionGroup>
        </configSections>
    
        <TestSectionGroup>
            <TestSection>
                <add key="name" value="NameTesting"></add>
                <add key="version" value="1.0"></add>
            </TestSection>
        </TestSectionGroup>
    </configuration>
    
    紧接着我们就可以在程序部分。
     
    首先,我们需要一个TestHandler对象,来处理这个节点,并且这个对象必须要实现IConfigurationSectionHandler这个接口
     
    这个接口就只有一个方法   
    object Create(object parent, object configContext, XmlNode section)
    之后就可以在此进行处理了
     
    比如我这里
        public class TestHandler : IConfigurationSectionHandler
        {
            public object Create(object parent, object configContext, XmlNode section)
            {
                NameValueCollection configs;
                NameValueSectionHandler baseHandler = new NameValueSectionHandler();
                configs = (NameValueCollection)baseHandler.Create(parent, configContext, section);
                return configs;
            }
        }
    

    主要功能即用NameValueCollection对象读出add 节点的属性结合,之后返回这个collection
     
    之后怎样在程序中调用这个呢,也非常简单,使用ConfigurarionManager 对象里的GetSection 就ok了,
    他会自动调用IConfigurationSectionHandler里的Create方法。
     
            static void Main(string[] args)
            {
                Object o = ConfigurationManager.GetSectio("TestSectionGroup/TestSection");
    
            }
    

    此时这里的o 就是Create返回的那个configs了
     
     
    ===================
    有何意义?
    -------------
    可以在web.config 配置某个section,之后这个section里的内容为其他某个单独的xml页面的地址
    我们就可以通过IConfigurationSectionHandler的Create 方法处理,
    读出这个独立的Xml,进行相应的操作,
    配置就不用全写在web.config 或app.config 上了
     
     

  • 相关阅读:
    上下界网络流——概念解析与快速入门(待修改)
    maomao的现在与未来
    exgcd证明和最基础应用
    快速入门Splay
    luogu 2515
    bzoj 1996
    *51nod 1409
    51nod 1412
    51nod 1503
    51nod 1020
  • 原文地址:https://www.cnblogs.com/jicheng1014/p/1875097.html
Copyright © 2011-2022 走看看