子树上的xpath搜索 [英] xpath search on subtree
问题描述
我需要将xpath节点搜索限制为子树。我目前正在使用下面的方法,但它会在整个文档中搜索我是否给它提供文档或我要搜索的节点。
I need to restrict the xpath node search to a subtree. I'm currently using the method below but it searches on a whole document regardlest whether I give it the document or the node I want to search from.
private NodeList findNodes(Object obj,String xPathString) throws ... {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile(xPathString);
return (NodeList) expression.evaluate(obj, XPathConstants.NODESET);
}
我现在使用的解决方案是我创建新文档,追加节点并搜索新文档,然后合并。我想改进这个。可以吗?
Solution I'm using now is that I create new document, append the node and search on the new document, then merge. I want to improve this. Can it be done?
我使用的XPath是 // nodeName
。
The XPath I'm using is //nodeName
.
推荐答案
您正在//轴上查找'文件根的任何后代节点',
You're looking on the // axis which means 'any descendant node of the document root',
将其更改为.// axis(上下文节点的后代),它将按预期工作。
Change it to .// axis (descendands of the context node) and it will work as expected.
这篇关于子树上的xpath搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!