I am facing some kind of a weird(as it appears to me) problem. I have a NodeList and need to remove an element from the NodeList while iterating through it. The NodeList has only one child element , so after removing that element that NodeList does not have any child element. Ideally the for loop should have stopped after removal of that element, but this is not happening and as the for loop runs for the second time, even when there are no child elements available, I am getting a NullPointerException.
Sample XML :
<Order OrderNo="1">
<Lines>
<Line LineNo="1"/>
</Lines>
</Order>
Sample Code :
NodeList nlLine = inDoc.getElementsByTagName("Line");
for(int cntLn = 0 ; cntLn < nlLine.getLength() ; cntLn++){
Element elLn = (Element) nlLine.item(cntLn);
if(//some condition){
elLn.getParentNode().removeChild(elLn);
cntLn--;
}
}
I am getting NullPointer exception on the linewhere i am getting the Parent Node and then removing the child. Any clue/lead/help on this?
You are decrementing the loop variable cntLn--
.
I am pretty sure you meant to increment it cntLn++
. And since you are already incrementing, just omit the line cntLn--;
TIP: As a healthy coding practice, always use the prefix increment operator ++cntLn
in case of loops (unless you explicitly need the postfix behavior).