Search code examples
xmlxpathdomdocument

Remove a node using xpath


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.


Solution

  • 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);