3

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:

<?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:

      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:

<categories>
 <category label="6 seconds"/>
 <category label="12 seconds"/>
 <category label="3 seconds"/>
 <category label="6 seconds"/>
 <category label="9 seconds"/>
      .....
      .....
 </categories>
3
  • when i try to print c value from for loop it is printing only half of the size of list value. Commented Jul 10, 2012 at 11:12
  • It is solved when i doesn't increment "c" value in loop. but i don't know why can somebody please explain me. Commented Jul 10, 2012 at 11:17
  • 1
    When you delete node 0, all nodes shift left. So node one becomes node 0. Then you attempt to delete node 1, nut never go back to delete node 0 again. So you completely missed the original node 1. Commented Sep 8, 2013 at 21:36

1 Answer 1

6

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

Node categories = doc.getElementsByTagName("categories").item(0);
NodeList categorieslist = categories.getChildNodes();
while (categorieslist.getLength() > 0) {
    Node node = categorieslist.item(0);
    node.getParentNode().removeChild(node);
}
Sign up to request clarification or add additional context in comments.

1 Comment

but why it is deleting alternative nodes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.