2

我有一个国家/地区的 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 会包含换行符。

4

1 回答 1

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
于 2012-07-28T12:15:41.750 回答