I have an xml structure as follows:
<a>
<b>
<foo>null</foo>
</b>
<b>
<foo>abc</foo>
</b>
<b>
<foo>efg</foo>
</b>
</a>
I am using org.w3c.dom.Document
to update the nodes. when <foo>
has a value null
, I want to remove
<b>
<foo>null</foo>
</b>
Is this possible? I know I can call removeChild(childElement)
, but not sure how I can specify to remove the specific nested element above.
Update: With the answer below, I tried:
String query = "/a/b[foo[text() = 'null']]";
Object result = (xpath.compile(newQuery)).evaluate(doc, NODE);
NodeList nodes = (NodeList)result;
for (int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
doc.removeChild(node);
}
I get NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist
.
To remove a node from the XML Document Object Model (DOM), use the RemoveChild method to remove a specific node. When you remove a node, the method removes the subtree belonging to the node being removed; that is, if it is not a leaf node.
node() matches any node (the least specific node test of them all) text() matches text nodes only. comment() matches comment nodes. * matches any element node.
doc.removeChild(node);
will not work because the node you're trying to remove isn't a child of the document node, it's a child of the document element (the a
), which itself is a child of the document root node. You need to call removeChild
on the correct parent node:
node.getParentNode().removeChild(node);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With