SaNtoRiaN
SaNtoRiaN

Reputation: 2202

Java delete xml nodes using dom

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)

Upvotes: 0

Views: 1398

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

If the sample you have shown is your complete XML document then I think all you need is doc.getDocumentElement().setTextContent("") which will remove all child nodes of the document element.

Upvotes: 3

Related Questions