I'm using dom to deal with my xml file, I have an input on the form
<students>
<tableRow>
<id>1</id>
<name>ams</name>
<grade>100</grade>
</tableRow>
<tableRow>
<id>1</id>
<name>ams</name>
<grade>100</grade>
</tableRow>
</students>
I want to delete all nodes to be on the form
<students>
</students>
I've tried the following code
Node node = doc.getFirstChild();
while (node.hasChildNodes())
node.removeChild(node.getFirstChild());
and this one
NodeList list = doc.getElementsByTagName("tableRow");
Node node = doc.getFirstChild();
for(int i = 0; i < list.getLength(); i++)
node.removeChild(list.item(i));
but none of them worked. Any suggestions?
update
I got this exception
org.w3c.dom.DOMException: NO_MODIFICATION_ALLOWED_ERR: An attempt is made to modify an object where modifications are not allowed. at com.sun.org.apache.xerces.internal.dom.ParentNode.internalRemoveChild(Unknown Source) at com.sun.org.apache.xerces.internal.dom.ParentNode.removeChild(Unknown Source)
NodeLists are live collection so you would need to remove items from the end of the NodeList in your loopfor (int i = list.getLength() - 1; i >=0; i--) { Node child = list.item(i); child.getParentNode().removeChild(child); }.