我正在使用此代码,但我不确定XPath表达式应该是什么样的。
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xpath.compile("XXXX");
NodeList nodes = (NodeList) expression.evaluate(doc.getDocumentElement(), XPathConstants.NODESET);
假设有一棵树:
<animal>
<big>
<elephant>
<white_elephant>
</white_elephant>
</elephant>
</big>
<small>
</small>
</animal>
我想让节点的每个后代变大:( elephant , white_elephant )+ big 本身
答案 0 :(得分:3)
您可以使用descendant-or-self
- 轴:
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xpath.compile("//big/descendant-or-self::*");
NodeList nodes = (NodeList) expression.evaluate(doc.getDocumentElement(), XPathConstants.NODESET);
维基百科是获取不同轴概述的好来源:http://en.wikipedia.org/wiki/XPath#Axis_specifiers
编辑:正如Jens Erat在评论中提到的,您可以将/descendant-or-self::
缩短为//
- 它只是缩写:
XPathExpression expression = xpath.compile("//big//*");