一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Xml文档进行操作 修改,删除

时间:2011-03-02 编辑:简简单单 来源:一聚教程网

xml文档进行操作 修改,删除

下面我们来看看如何对上面的xml文档进行删除和修改的操作:

其实很简单,大概也是分一下几个步骤:

1、将xml文档加载到内存中

2、找到要删除的节点(根据条件)

3、重新保存加载xml文档

根据代码具体来看看如何操作

删除

 

  protected void button1_click(object sender, eventargs e)
    {
        xmldocument doc = new xmldocument();
        string path = server.mappath("~/product.xml");
        doc.load(path);
        xmlnodelist xmlnodelist = doc.selectnodes("//products//product");
        foreach (xmlnode xmlnode in xmlnodelist)
        {
            if(xmlnode.attributes["id"].value=="4")
            {

               //找到父节点,从父节点删除该节点
                xmlnode.parentnode.removechild(xmlnode);
            }
        }
        doc.save(path);
    }

当然了,也可以删除通过romoveallattributes,removeattribute或removeattributeat等来删除属性

修改:

 

protected void button2_click(object sender, eventargs e)
    {
        xmldocument xmldocument = new xmldocument();
        string path = server.mappath("~/product.xml");
        xmldocument.load(path);
        string xmlpath = "//products//product";

        //根据路径找到所有节点
        xmlnodelist nodelist = xmldocument.selectnodes(xmlpath);

       //循环遍历这些子
        foreach (xmlnode node in nodelist)
        {

             //根据节点的某个属性找到要操作的节点
            if(node.attributes["id"].value=="4")
            {

                //对节点进行修改操作
                node.attributes["proname"].value = "aa1";
                node.attributes["proprice"].value = "12";
                node.attributes["proinfo"].value = "bb";
            }
           
        }

        //重新加载保存
        xmldocument.save(path);
    }

上面是对xml进行的修改的操作,删除基本和它差不多

 

前端时间,在一本项目教材书上,看到他们对xml文档处理的时候,在查找节点的时候用的是索引

xmlnode xmlnode = doc.selectsinglenode("//products//product[5]");

xml



 
 

 
 

 
 

 
 

 
 

 

热门栏目