我有这个 XML 实例文档:
<entities>
<person>James</person>
<person>Jack</person>
<person>Jim</person>
</entities>
通过以下代码,我迭代人员节点并打印他们的名字:
XPathExpression expr = xpath.compile("/entities/person");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0 ; i < nodes.getLength() ; i++) {
Node node = nodes.item(i);
String nodeName = node.getNodeName();
String name = xpath.compile("text()").evaluate(node).trim();
System.out.printf("node type = %s, node name = %s\n", nodeName, name);
}
现在我想要的是还可以访问每个节点的索引。
我知道我可以轻松地从 i
循环变量中获取它,但我想将其作为 XPath 表达式获取,最好以与我获取的方式没有不同的方式text()
XPath 表达式的值。
我的用例是,我试图处理我作为 XPath 表达式(我在运行时从配置文件加载)收集的所有属性,以便最大限度地减少非通用代码,所以我不想将索引视为特殊情况。
最佳答案
你必须使用一个技巧,比如计算前面的 sibling
count(preceding-sibling::person)
第一个人的值为 0,第二个人的值为 1,依此类推。
关于Java XPath : iterating over a collection of nodes and their indices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17346078/