您的位置:首页 > 其它

读取自定义的config文件

2009-03-27 10:18 288 查看
我们都知道web.config 的读取方法有两种

1、使用System.Configuration 的 ConfigurationManager 读取


ConfigurationManager.AppSettings["key"].ToString();
2、使用AppSettingReader进行读取


AppSettingsReader reader = new AppSettingsReader();


reader.GetValue("key", typeof(string)) as string;

很多时候我们需要自己定义些Config文件,这些需要怎么去读呢?
首先我们新建一个Config文件,命名为Test.config,当然里面的内容都是不需要的,因为我们要自己定义,所以把它们都删除掉
接着写我们自己的内容(哦,对了,config文件事实上就是一个XML文件,所以第一句声明必须有的)


<?xml version="1.0" ?>


<templates>


<template templateID="welcome_Template">


<subject id="sd" name="top">


<![CDATA[


##ContentTitle## has ##ContentAction##


]]>


</subject>


<bodyHtml>


<![CDATA[


<div>


<p>


Content Title : ##ContentTitle##


</p>


<p>


If the link is blocked, please copy the url below to view detail.<br />


URL: http://##ContentDocumentGUID##

</p>


<p style="text-align:right; padding:10px;">


Best Regards.


</p>


</div>


]]>


</bodyHtml>


</template>


</templates>

好了,上面就是我们自己写的config文件了,接下来就要进行读取操作了


XmlTextReader reader = new XmlTextReader(Server.MapPath("Template.config")); // new一个XMLTextReader实例


XmlDocument doc = new XmlDocument();


doc.Load(reader);//


reader.Close();//关闭reader,不然config文件就变成只读的了


XmlNodeList nodeList = doc.SelectSingleNode("/templates").ChildNodes;


foreach (XmlNode n in nodeList)






{


//XmlNode 的Attributes属性是列出这个Node的所以属性,比如我们定义的template有个属性叫templateID


if (n.Attributes["templateID"].Value == "welcome_Template")






{


// 再遍历取这个node的子node




foreach (XmlNode node in n.ChildNodes)


Response.Write(node.Name + node.InnerText + "<hr />");




}


}

嗯,这样就可以读取我们自己写的config文件了
还有一点,对于每个XmlNode,如果我们要取得它的所有属性可以用下面的代码


XmlAttributeCollection xmlAttrList = node.Attributes;


foreach (XmlAttribute attr in xmlAttrList)






{


// Action


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: