Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all values in a list of objects with xpath?

Tags:

java

xml

xpath

How can I get the name of all accounts with xpath? The following expression does only return the first accounts name:

XPathExpression fax = xpath.compile("/accounts/account/name")

<accounts>
<account>
<name>Johndoe1<name>
<account>
<account>
<name>Johndoe2<name>
<account>
</account>
like image 535
membersound Avatar asked Dec 05 '12 10:12

membersound


2 Answers

According to this tutorial : http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html you need to do something like this :

XPathExpression fax = xpath.compile("/accounts/account/name")
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getNodeValue()); 
}
like image 171
koopajah Avatar answered Nov 09 '22 15:11

koopajah


That is the correct XPath expression, but the result you get depends on how you evaluate it. The XPath expression /accounts/account/name returns a node set containing (in document order) all the name child elements of all the account elements under the accounts root element in the document.

In the XPath data model the string value of a node set is defined to be the string value of the first node in the set. So if you use the single-argument evaluate:

fax.evaluate(someDocument)

this will evaluate the expression as a string and you'll just get the first name value. Instead you need to evaluate the expression as a node set, then extract the string value of each node in turn, as suggested in koopajah's answer.

like image 39
Ian Roberts Avatar answered Nov 09 '22 16:11

Ian Roberts