获取.config文件节点的一些方法

经常要把一些配置数据比如URL,栏目名称,应用程序集等放在.config里面,如果全部放在web.config会显得比较凌乱,通常的做法是建立一些其他的*.config文件里面,下面的方法可以通用与读取*.config文件的节点值:

System.Web.HttpContext.Current.Request.MapPath(file)  //首先用MapPath方法获取该config文件的物理位置

XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(filepath);//把这个config文件装载起来,

if(xmlDoc.GetElementsByTagName(parentNodeName).Count>0) //检查有没有这个节点
     {
      XmlNode parentNode = xmlDoc.GetElementsByTagName(parentNodeName).Item(0);//获取叫这个名字的第一个节点
foreach(XmlNode curNode in parentNode.ChildNodes) //接下来就是递归
      {
       if(curNode.LocalName==curName)
       {
        key = curNode.Attributes[keyName].Value;              //读key
        curvalue = curNode.Attributes[valueName].Value; //读value
        ht.Add(key,curvalue);
       }
      }

return ht;

posted on 2007-09-28 12:28  石川  阅读(252)  评论(0编辑  收藏  举报