Take the 2-minute tour ×

Following is the XML file -

    <C>New Delhi</C>

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();
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;
    node = nodes.item(i);
    String city = xpath.evaluate("C",node);
    out.write(" " + city + "\r\n");

Can somebody help me to get the required output?

share|improve this question
So your question is how to write the city to file? –  Rudy Apr 18 '12 at 5:42
@Rudy - Yes... only CITIES... –  John Apr 18 '12 at 5:50
When you said unable, which line does throw you the error? –  Rudy Apr 18 '12 at 5:52
@Rudy- NO ERROR... but I am getting only FIRST City name out of the total 3 Group. Where as I want all the Cities. :( –  John Apr 18 '12 at 6:03

1 Answer 1

up vote 1 down vote accepted

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.


XPathExpression expr = xpath.compile("//Country/Group/C");
    node = nodes.item(i);
    out.write(" " + node.getTextContent() + "\n");
share|improve this answer
what changes to do? I didnt get the exact required output..!! –  John Apr 18 '12 at 6:50
the code worked very well and output was as required.. Thanks a lot –  John Apr 18 '12 at 7:03

Your Answer


