繁体   English   中英

如何使用Java从XML节点组中获取文本?

[英]How to get the text from the group of XML nodes using Java?

以下是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将城市的名称保存到文本文件中-以下是无法满足需要的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();
.....
.....

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

您只得到第一个城市,因为这就是您要的。 您的第一个XPATH表达式返回所有Group节点。 您遍历这些变量并评估相对于每个Group的XPATH C ,从而返回一个城市。

只需将第一个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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM