如何使用xpath获取对象列表中的所有值?

mem*_*und 6 java xml xpath

如何使用 xpath 获取所有帐户的名称?以下表达式仅返回第一个帐户名称:

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

<accounts>
<account>
<name>Johndoe1<name>
<account>
<account>
<name>Johndoe2<name>
<account>
</account>
Run Code Online (Sandbox Code Playgroud)

koo*_*jah 7

根据本教程:http : //www.ibm.com/developerworks/library/x-javaxpathapi/index.html你需要做这样的事情:

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()); 
}
Run Code Online (Sandbox Code Playgroud)