我有一个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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句