我有一个国家的XML列表如下:
<countries>
<country>
<code>CA</code>
<country>Canada</country>
</country>
... etc...
</countries>
我想选择节点并迭代它们,所以使用
path "/countries/*"
然后在JavaScript中:
nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
当我迭代时,我发现第一个和第三个节点是空格(换行符),第二个和第四个节点是我想要的实际XML。
如何使用XPath忽略空白节点?我只对XML部分感兴趣,我不能保证XML会包含换行符。
答案 0 :(得分:0)
你不能使用像这样的简单程序吗?
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