以下是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&amp; amp;将City的名称保存到文本文件中。 XPath - 下面是无法满足需要的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();
.....
.....
有人可以帮助我获得所需的输出吗?
答案 0 :(得分:1)
您只获得了第一个城市,因为这就是您所要求的。您的第一个XPATH表达式返回所有Group
个节点。您迭代这些并评估相对于每个C
的XPATH Group
,返回一个城市。
只需将第一个XPATH更改为//Country/Group/C
并完全消除第二个XPATH - 只需打印第一个XPATH返回的每个节点的文本值。
即:
XPathExpression expr = xpath.compile("//Country/Group/C");
...
for (int i = 0; i < nodes.getLength(); i++)
{
node = nodes.item(i);
out.write(" " + node.getTextContent() + "\n");
}