简体   繁体   English

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

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

Following is the XML file - 以下是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>

I want to save the name of Cities to a text file using Java & XPath - Below is the Java code which is unable to do the needful. 我想使用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();
.....
.....

Can somebody help me to get the required output? 有人可以帮助我获得所需的输出吗?

You are getting only the first city because that's what you asked for. 您只得到第一个城市,因为这就是您要的。 Your first XPATH expression returns all the Group nodes. 您的第一个XPATH表达式返回所有Group节点。 You iterate over these and evaluate the XPATH C relative to each Group , returning a single city. 您遍历这些变量并评估相对于每个Group的XPATH C ,从而返回一个城市。

Just change the first XPATH to //Country/Group/C and eliminate the second XPATH altogether -- just print the text value of each node returned by the first XPATH. 只需将第一个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");
}

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

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