我們都知道web.config 的讀取方法有兩種:
1、使用System.Configuration 的 ConfigurationManager 讀取
ConfigurationManager.AppSettings["key"].ToString();
2、使用AppSettingReader進行讀取
AppSettingsReader reader = new AppSettingsReader();<br /> reader.GetValue("key", typeof(string)) as string;
很多時候我們需要自己定義些Config檔案,這些需要怎麼去讀呢?
首先我們建立一個Config檔案,命名為Test.config,當然裡面的內容都是不需要的,因為我們要自己定義,所以把它們都刪除掉
接著寫我們自己的內容(哦,對了,config檔案事實上就是一個XML檔案,所以第一句聲明必須有的)
<?xml version="1.0" ?><br /><templates><br /> <template templateID="welcome_Template"><br /> <subject id="sd" name="top"><br /> <!--[CDATA[<br /> ##ContentTitle## has ##ContentAction##<br /> ]]><br /> </subject><br /> <bodyHtml><br /> <![CDATA[<br /> <div><br /> <p><br /> Content Title : ##ContentTitle##<br /> </p><br /> <p><br /> If the link is blocked, please copy the url below to view detail.<br /><br /> URL: http://##ContentDocumentGUID##<br /> </p><br /> <p style="text-align:right; padding:10px;" mce_style="text-align:right; padding:10px;"><br /> Best Regards.<br /> </p><br /> </div><br /> ]]--><br /> </bodyHtml><br /> </template><br /></templates></p><p>
好了,上面就是我們自己寫的config檔案了,接下來就要進行讀取操作了
XmlTextReader reader = new XmlTextReader(Server.MapPath("Template.config")); // new一個XMLTextReader執行個體<br /> XmlDocument doc = new XmlDocument();<br /> doc.Load(reader);//<br /> reader.Close();//關閉reader,不然config檔案就變成唯讀了<br /> XmlNodeList nodeList = doc.SelectSingleNode("/templates").ChildNodes;<br /> foreach (XmlNode n in nodeList)<br /> {<br />//XmlNode 的Attributes屬性是列出這個Node的所以屬性,比如我們定義的template有個屬性叫templateID<br /> if (n.Attributes["templateID"].Value == "welcome_Template")<br /> {<br /> // 再遍曆取這個node的子node</p><p> foreach (XmlNode node in n.ChildNodes)<br /> Response.Write(node.Name + node.InnerText + "<hr />");</p><p> }<br /> }</p><p>
嗯,這樣就可以讀取我們自己寫的config檔案了
還有一點,對於每個XmlNode,如果我們要取得它的所有屬性可以用下面的代碼
XmlAttributeCollection xmlAttrList = node.Attributes;<br /> foreach (XmlAttribute attr in xmlAttrList)<br /> {<br /> // Action<br /> }
http://www.cnblogs.com/chenjilv/archive/2008/05/20/1203236.html