zoukankan      html  css  js  c++  java
  • 对Xml文档进行操作(修改,删除)

    <?xml version="1.0" encoding="utf-8"?>
    <Products>
      <Product id="0" proName="aa1" proPrice="12" proInfo="bb">
      </Product>
      <Product id="1" proName="电脑" proPrice="3200" proInfo="电脑电脑电脑电脑电脑电脑">
      </Product>
      <Product id="2" proName="mp4" proPrice="400" proInfo="mp4mp4mp4mp4mp4mp4mp4mp4mp4">
      </Product>
      <Product id="3" proName="mp4" proPrice="400" proInfo="mp4mp4mp4mp4mp4mp4mp4mp4mp4">
      </Product>
      <Product id="4" proName="mp5" proPrice="500" proInfo="mp5mp5mp5mp5mp5mp5mp5mp5mp5">
      </Product>
    </Products>

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

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

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

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

    3、重新保存加载xml文档

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

    修改:

      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进行的修改的操作,删除基本和它差不多

    删除

       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等来删除属性

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

    XmlNode xmlNode = doc.SelectSingleNode("//Products//Product[5]");

    本人认为这种方法不可取,我们一般都会让你一个id对应一个节点,如果采取这种方式,那么很可能无法找到需要的节点,造成程序方面的错误,这是本人的一些见解,大家有什么意见可以提出来,共同学习!

    多思考,多创新,才是正道!
  • 相关阅读:
    Spring Boot 使用常见问题
    JPA 使用
    JPA 复杂查询
    Gitlab利用Webhook实现Push代码后的jenkins自动构建
    消息中间件的使用场景
    消息中间件资料整理
    js原生跨域--用script标签实现
    遍历类成员并赋值
    Spring boot 读取 application.properties 文件方法
    fastjson 进行json转实体类对象及一些常用操作
  • 原文地址:https://www.cnblogs.com/shuang121/p/1967799.html
Copyright © 2011-2022 走看看