使用xpath删除节点

rga*_*ber 4 xml xpath domdocument

我有一个xml结构如下:

<a>
   <b>
      <foo>null</foo>
   </b>
   <b>
      <foo>abc</foo>
   </b>
   <b>
      <foo>efg</foo>
   </b>
</a>
Run Code Online (Sandbox Code Playgroud)

org.w3c.dom.Document用来更新节点.当<foo>有值时null,我想删除

<b>
  <foo>null</foo>
</b>
Run Code Online (Sandbox Code Playgroud)

这可能吗?我知道我可以调用removeChild(childElement),但不知道如何指定删除上面的特定嵌套元素.

更新:通过以下答案,我试过:

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);
}
Run Code Online (Sandbox Code Playgroud)

我得到NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.

Ian*_*rts 7

doc.removeChild(node);
Run Code Online (Sandbox Code Playgroud)

因为您尝试删除的节点不是文档节点的子节点,它将不起作用,它是文档元素(子)的子节点,它a本身是文档根节点的子节点.您需要调用removeChild正确的父节点:

node.getParentNode().removeChild(node);
Run Code Online (Sandbox Code Playgroud)