遍历读取XML文件及web.config的动态更新

border="0" src="http://forum.booye.com/byhtm/1.html" frameborder="0" width="470" height="60">

web.config文件是一个配制文件,我们会经常在里面写一些信息,供程序使用,......

时间有限,(用一个算法)

前段时间一直在忙,在公司时不太方便写,所以当时只是发了一个题目上去,目的是怕我忘记,我这个比较笨,呵呵,俗话说好脑筋不如一个烂笔头。本想回到家去完成这个帖子,主要还是一部电视吸引啦我,所以一直没有去。今天抽空把代码写好

大家指点指点:

遍历读取XML文件

XmlDocument doc = new XmlDocument(); //建立文档对象
   try
   {
    doc.Load("xml.xml"); //加载XML文档
    XmlNode root=doc.DocumentElement; //获取文档根节点
    XmlNode tempNode;
    if (root.HasChildNodes)
     tempNode=root.FirstChild; //根节点的第一个子节点
    else
     tempNode=root;

    while(tempNode!=root)
    {
     Console.Write(tempNode.Name);  //输出节点名称
     tempNode=tempNode.FirstChild;  //获取节点的子节点
     if(tempNode.GetType().Name == "XmlText")  //判断是否是内容节点
     {
      Console.WriteLine(": "+tempNode.Value);  //输出内容节点的值
      while(tempNode.NextSibling==null && tempNode!=root)
      {
       tempNode=tempNode.ParentNode;
      }
      if(tempNode!=root)
       tempNode=tempNode.NextSibling;  //获取下一个节点
     }
     else
     {
      Console.WriteLine();
     }
    }
   }
   catch   {
   }

web.config的动态更新

XmlDocument document = new XmlDocument();
   document.Load("web.config");
   
   //XmlNodeList childNodes = document.SelectNodes("configuration/appSettings/add");
   XmlNodeList childNodes = document.SelectSingleNode("configuration/appSettings").ChildNodes;
   try
   {
    foreach (XmlNode node in childNodes)
    {
     XmlElement element = null;
     try
     {
      element = (XmlElement) node;//注释也属于节点,所以在转化时可能会出现类型转化错误。
             //使用SelectNodes不会出现这个问题。使用那个你选择,在这里主要目的是比较两种方法的使用
      if (element.Attributes["key"].InnerText == strKeyName)
      {
       element.Attributes["value"].InnerText = strKeyValue;
       document.Save("web.config");
      }
     }
     catch{}
    }
   }
   catch (Exception exception)
   {
    throw exception;
   }

border="0" src="http://forum.booye.com/byhtm/2.html" frameborder="0" width="470" height="60">
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值