我的xml结构如下:
<a>
<b>
<foo>null</foo>
</b>
<b>
<foo>abc</foo>
</b>
<b>
<foo>efg</foo>
</b>
</a>
我正在使用 org.w3c.dom.Document
更新节点。什么时候<foo>
有一个值 null
, 我想删除
<b>
<foo>null</foo>
</b>
这可能吗?我知道我可以打电话 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);
}
我得到 NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist
.
最佳答案
doc.removeChild(node);
将不起作用,因为您尝试删除的节点不是文档节点的子节点,它是文档元素(a
)的子节点,它本身是文档根节点的子节点。您需要在正确的父节点上调用 removeChild
:
node.getParentNode().removeChild(node);
关于xml - 使用 xpath 删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21839656/