从 XML 文件中删除节点 java 程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11411604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:59:36  来源:igfitidea点击:

remove node from XML file java program

javaxml

提问by mallikarjun

When I try to remove a node from XML node from java program it is giving me a strange problem. It is removing alternate nodes. I have to remove existing nodes before inserting new nodes. my xml file is:

当我尝试从 Java 程序的 XML 节点中删除一个节点时,它给了我一个奇怪的问题。它正在删除备用节点。在插入新节点之前,我必须删除现有节点。我的 xml 文件是:

<?xml version="1.0" encoding="windows-1252" ?>
<chart>
<categories>
 <category label="3 seconds"/>
 <category label="6 seconds"/>
 <category label="9 seconds"/>
 <category label="12 seconds"/>
</categories>

</chart>

my java program is:

我的java程序是:

      DocumentBuilderFactory  docFactory  = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

      Document doc = docBuilder.parse(filePath);


      Node categories = doc.getElementsByTagName("categories").item(0);

      NodeList categorieslist = categories.getChildNodes();

      // if exists delete old data the insert new data.


      for (int c = 0; c < categorieslist.getLength(); c++) {

        Node node = categorieslist.item(c);
        categories.removeChild(node);
      }
    for(int i=1;i<20;i++){

    Element category = doc.createElement("category");
    category.setAttribute("label",3*i+" seconds");
    categories.appendChild(category);
  }

This code is deleting alternative nodes I don't know why. The resulting XML is showing like this:

此代码正在删除替代节点,我不知道为什么。生成的 XML 显示如下:

<categories>
 <category label="6 seconds"/>
 <category label="12 seconds"/>
 <category label="3 seconds"/>
 <category label="6 seconds"/>
 <category label="9 seconds"/>
      .....
      .....
 </categories>

回答by Anton

Every time you remove a child the list becomes shorter, the list isn't a static collections, so every time you call getLength() you get the actual size

每次删除孩子时,列表都会变短,列表不是静态集合,因此每次调用 getLength() 时都会得到实际大小

Node categories = doc.getElementsByTagName("categories").item(0);
NodeList categorieslist = categories.getChildNodes();
while (categorieslist.getLength() > 0) {
    Node node = categorieslist.item(0);
    node.getParentNode().removeChild(node);
}