简体   繁体   中英

Java XPath : iterating over a collection of nodes and their indices

I have this XML instance document:

<entities>
    <person>James</person>
    <person>Jack</person>
    <person>Jim</person>
</entities>

And with the following code I iterate over the person nodes and print their names:

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);
}

Now what I would like is to also have access to the index of each node.

I know I can trivially get it from the i loop variable but I want to get it as an XPath expression instead, preferably in no different way than I get the value of the text() XPath expression.

My use-case is that I am trying to handle all attributes I collect as XPath expressions (which I load at run-time from a config file) so that I minimize non-generic code, so I don't want to treat the index as a special case.

You'd have to use a trick like counting the preceding siblings

count(preceding-sibling::person)

which gives 0 for the first person , 1 for the second one, etc.

尝试使用position()

String index  = xpath.compile("position()").evaluate(node).trim();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM