operate XML file(update,delete)

4. update value in XML file
XmlNodeList nodeList=xmlDoc.SelectSingleNode("bookstore").ChildNodes;//获取bookstore节点的所有子节点
   foreach(XmlNode xn in nodeList)//遍历所有子节点
   {
    XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
    if(xe.GetAttribute("genre")=="李赞红")//如果genre属性值为“李赞红”
    {
     xe.SetAttribute("genre","update李赞红");//则修改该属性为“update李赞红”
 
     XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
     foreach(XmlNode xn1 in nls)//遍历
     {
      XmlElement xe2=(XmlElement)xn1;//转换类型
      if(xe2.Name=="author")//如果找到
      {
       xe2.InnerText="亚胜";//则修改
       break;//找到退出来就可以了
      }
     }
     break;
    }
   }
    xmlDoc.Save("bookstore.xml");//保存

5.delete node in XML file
 Sample1:
XmlNodeList xnl=xmlDoc.SelectSingleNode("bookstore").ChildNodes;
 
   foreach(XmlNode xn in xnl)
   {
    XmlElement xe=(XmlElement)xn;
    if(xe.GetAttribute("genre")=="fantasy")
    {
     xe.RemoveAttribute("genre");//删除genre属性
    }
    else if(xe.GetAttribute("genre")=="update李赞红")
    {
     xe.RemoveAll();//删除该节点的全部内容
    }
   }
   xmlDoc.Save("bookstore.xml");
the result is the following:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
  <book>
  </book>
</bookstore>

Sample2:
XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(HttpContext.Current.Server.MapPath("user.config"));
       
        XmlNodeList nodelist = xmldoc.SelectSingleNode("users").ChildNodes;
        Boolean find = false;
        foreach (XmlNode nd in nodelist)
        {
            XmlElement ele = (XmlElement)nd;
            if (ele.GetAttribute("Login").ToString() == login)
            {
              
                //ele.RemoveAll();
////这样删除的话,会留下<user></user>这样的空值节点。
                xmldoc.DocumentElement.RemoveChild(nd);
//这样删除的话 是把整个节点删除,不会留下<user></user>这样的空值节点了。
                xmldoc.Save(HttpContext.Current.Server.MapPath("user.config"));
                return false;
            }
        }
        
the xml file is the following
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="fantasy" ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
</bookstore>

你可能感兴趣的:(update)