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>
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());
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With