1

以下是 XML 文件 -

<Country>
  <Group>
    <C>Tokyo</C>
    <C>Beijing</C>
    <C>Bangkok</C>
  </Group>
  <Group>
    <C>New Delhi</C>
    <C>Mumbai</C>
  </Group>
  <Group>
    <C>Colombo</C>
  </Group>
</Country>

我想使用 Java 和 XPath 将 Cities 的名称保存到文本文件中 - 下面是无法满足需要的 Java 代码。

.....
.....
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); 
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("Continent.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile("//Country/Group");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
BufferedWriter out = new BufferedWriter(new FileWriter("Cities.txt"));
Node node;
for (int i = 0; i < nodes.getLength(); i++) 
{
    node = nodes.item(i);
    String city = xpath.evaluate("C",node);
    out.write(" " + city + "\r\n");
}
out.close();
.....
.....

有人可以帮我获得所需的输出吗?

4

1 回答 1

1

你得到的只是第一个城市,因为那是你所要求的。您的第一个 XPATH 表达式返回所有Group节点。您遍历这些并评估C相对于 each的 XPATH Group,返回一个城市。

只需将第一个 XPATH 更改为//Country/Group/C并完全消除第二个 XPATH —— 只需打印第一个 XPATH 返回的每个节点的文本值。

IE:

XPathExpression expr = xpath.compile("//Country/Group/C");
...
for (int i = 0; i < nodes.getLength(); i++) 
{
    node = nodes.item(i);
    out.write(" " + node.getTextContent() + "\n");
}
于 2012-04-18T06:16:23.457 回答