简体   繁体   中英

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

Following is the XML file -

<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.

.....
.....
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. You iterate over these and evaluate the XPATH C relative to each Group , returning a single city.

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.

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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