我们都知道web.config 的读取方法有两种

1、使用System.Configuration 的 ConfigurationManager 读取

读取自定义的config文件ConfigurationManager.AppSettings["key"].ToString();

2、使用AppSettingReader进行读取

读取自定义的config文件        AppSettingsReader reader = new AppSettingsReader();
读取自定义的config文件        reader.GetValue(
"key"typeof(string)) as string;

很多时候我们需要自己定义些Config文件,这些需要怎么去读呢?
首先我们新建一个Config文件,命名为Test.config,当然里面的内容都是不需要的,因为我们要自己定义,所以把它们都删除掉
接着写我们自己的内容(哦,对了,config文件事实上就是一个XML文件,所以第一句声明必须有的)
读取自定义的config文件<?xml version="1.0" ?>
读取自定义的config文件
<templates>
读取自定义的config文件  
<template templateID="welcome_Template">
读取自定义的config文件    
<subject id="sd" name="top">
读取自定义的config文件      
<![CDATA[
读取自定义的config文件      ##ContentTitle## has ##ContentAction##
读取自定义的config文件      
]]>
读取自定义的config文件    
</subject>
读取自定义的config文件    
<bodyHtml>
读取自定义的config文件      
<![CDATA[
读取自定义的config文件    <div>
读取自定义的config文件    <p>
读取自定义的config文件      Content Title : ##ContentTitle##
读取自定义的config文件    </p>
读取自定义的config文件    <p>
读取自定义的config文件      If the link is blocked, please copy the url below to view detail.<br />
读取自定义的config文件      URL: http://##ContentDocumentGUID##
读取自定义的config文件    </p>
读取自定义的config文件    <p style="text-align:right; padding:10px;">
读取自定义的config文件      Best Regards.
读取自定义的config文件    </p>
读取自定义的config文件    </div>
读取自定义的config文件    
]]>
读取自定义的config文件    
</bodyHtml>
读取自定义的config文件  
</template>
读取自定义的config文件
</templates>

好了,上面就是我们自己写的config文件了,接下来就要进行读取操作了
读取自定义的config文件        XmlTextReader reader = new XmlTextReader(Server.MapPath("Template.config")); // new一个XMLTextReader实例
读取自定义的config文件
        XmlDocument doc = new XmlDocument();
读取自定义的config文件        doc.Load(reader);
//
读取自定义的config文件
        reader.Close();//关闭reader,不然config文件就变成只读的了
读取自定义的config文件
        XmlNodeList nodeList = doc.SelectSingleNode("/templates").ChildNodes;
读取自定义的config文件        
foreach (XmlNode n in nodeList)
        }

嗯,这样就可以读取我们自己写的config文件了
还有一点,对于每个XmlNode,如果我们要取得它的所有属性可以用下面的代码
 
读取自定义的config文件        XmlAttributeCollection xmlAttrList = node.Attributes;
读取自定义的config文件        
foreach (XmlAttribute attr in xmlAttrList)
        }

相关文章: