码迷,mamicode.com
首页 > Web开发 > 详细

.Net——使用.net内置处理程序处理自定义节点Demo

时间:2015-06-22 22:21:27      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:.net   配置文件   


         在.net中,因为对不同的节点,都对应着类去对它进行处理,。net里面为了方便,已经内置了一些类供我们使用,使我们在读取配置文件时,不必自己去定义类去处理自己定义的自定义节点。


        下面我们写了这样一个配置文件:


          

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <!--使用IgnoreSection处理自定义节点-->
    <!--<section name="mailServeraddress" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false " restartOnExternalChanges="true"/>-->

    <section name="mailServeraddress" type="System.Configuration.SingleTagSectionHandler" />
    
    <!--注意,指定处理程序的配置文件要写在自定义配置文件的前面-->
  </configSections>
  
  
  <mailServeraddress address="mail.tracefact.net" username="lhc" password="124324"/>

 
</configuration>



              节点名称为:mailServeraddress,有三个属性,在section里定义了SingleTagSectionHandler来处理这个节点。


               

namespace 自定义节点和内置处理程序
{
    class Program
    {
        static void Main(string[] args)
        {
            ExampleSingleTagSectionHandler();

        }

        private static void ExampleSingleTagSectionHandler() {
            //SingleTagSectionHandler会以hashtable的形式返回节点的所有属性
            Hashtable mailServer = (Hashtable)ConfigurationManager.GetSection("mailServeraddress");//调用GetSection会返回一个hashtable

            string address = mailServer["address"].ToString();
            string username = mailServer["username"].ToString();
            string passWord = mailServer["password"].ToString();

            Console.WriteLine(address+"----"+username+"------"+passWord);

            
        }
    }
}

         

             配置文件写好后,调用GetSection强转hashtable后,就可以用key——value的形式读取节点的属性值了。


             在.net中,除了上面例子中的这个type,我们也可以使用其它内置type来处理自定义节点。












.Net——使用.net内置处理程序处理自定义节点Demo

标签:.net   配置文件   

原文地址:http://blog.csdn.net/lhc1105/article/details/46596333

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!