xml 使用 xpath 删除节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21839656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:00:04  来源:igfitidea点击:

Remove a node using xpath

xmlxpathdomdocument

提问by rgamber

I have an xml structure as follows:

我有一个 xml 结构如下:

<a>
   <b>
      <foo>null</foo>
   </b>
   <b>
      <foo>abc</foo>
   </b>
   <b>
      <foo>efg</foo>
   </b>
</a>

I am using org.w3c.dom.Documentto update the nodes. when <foo>has a value null, I want to remove

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

<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.

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

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.

我明白了NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist

回答by Ian Roberts

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 removeChildon the correct parent node:

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

node.getParentNode().removeChild(node);

回答by Kirill Polishchuk

To get that node you can use XPath:

要获取该节点,您可以使用 XPath:

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