Reputation: 75
hi i am having trouble in deleting XML node.
<Instance>
<Internal>
<Attribute>
<Name>length</Name>
</Attribute>
<Name>internal</Name>
</Internal>
<Name>Instanec</Name>
</Instance>
i want to delete Name Node so that my output is below.
<Instance>
<Internal>
<Attribute>
</Attribute>
</Internal>
</Instance>
i tried the following code :
NodeList baseElmntLst2 = doc.getElementsByTagName("Name");
for (int k = 0; k < baseElmntLst2.getLength(); k++) {
Element node = (Element) baseElmntLst2.item(k);
Element node2 = (Element) baseElmntLst2.item(k).getParentNode();
node2.removeChild(node);
}
but it does not delete all Name Elements which i dont understand.
Thankyou
Upvotes: 0
Views: 74
Reputation: 167436
DOM NodeList
s are live collections so if you want to delete all items in a NodeList
one way is to start at the end e.g. for (int k = baseElmntLst2.getLength(); k >= 0; k--)
. Or use while (baseElmntLst2.getLength() > 0) baseElmntLst2.item(0).getParentNode().removeChild(baseElmntLst2.item(0));
.
Upvotes: 1