Remove node with 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 use org.w3c.dom.Documentto update nodes. when <foo>it matters nulli want to delete

<b>
  <foo>null</foo>
</b>

Is it possible? I know what I can call removeChild(childElement), but I don’t know how I can specify to remove the specified 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 it NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.

+3
source share
2 answers
doc.removeChild(node);

, node, , node, (a), document root node. removeChild node:

node.getParentNode().removeChild(node);
+5

node, XPath:

/a/b[foo[text() = 'null']]
+3

All Articles