小小的储备知识:有关于读取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 上了
 
 

posted @ 2010-11-11 17:57  Atpking  阅读(728)  评论(0编辑  收藏  举报