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

时间:2012-07-10 10:42:00

标签: java xml

当我尝试从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>

我的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);
  }

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

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

1 个答案:

答案 0 :(得分:6)

每次删除子项时,列表都会变短,列表不是静态集合,因此每次调用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);
}