你不能用这样一个简单的程序吗?
NodeList countries = (NodeList) xpath.evaluate("//countries/country",
builder.parse(inputStream),
XPathConstants.NODESET);
for (int i = 0; i < countries.getLength(); i++) {
Node country = notes.item(i);
String code = (String) xpath.evaluate("./code/text()", country,
XPathConstants.STRING);
String name = (String) xpath.evaluate("./country/text()", country,
XPathConstants.STRING);
System.out.println(String.format("%s has country code %s", name, code));
}
与输入
<countries>
<country>
<code>CA</code>
<country>Canada</country>
</country>
<country>
<code>FR</code>
<country>France</country>
</country>
<country>
<code>IT</code>
<country>Italy</country>
</country>
<country>
<code>US</code>
<country>United States</country>
</country>
</countries>
输出
Canada has country code CA
France has country code FR
Italy has country code IT
United States has country code US