0

I have tried a lot of times but I did not how to retrive a value from XML using Java. I tried to use DOM and Xpath. Please help. I can use a String Writer to printout the XML so I know the XML is not empty.

Document doc = parseXML(connection.getInputStream());

doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("/xml_api_reply/weather/current_conditions/temp_f/text()");


Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getNodeValue()); 
}

The content of XML :

<xml_api_reply version="1">
  <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
    <current_conditions>
        <condition data="Clear"/>
        <temp_f data="49"/>
        <temp_c data="9"/>
    </current_conditions>
  </weather>
</xml_api_reply>

It seems that it did not go in to the for loop because nodes is null.

1

2 Answers 2

4

Your XPath expression evaluates to the (non existant) text-nodes underneath temp_f. Yet, you need the value of the data attribute:

/xml_api_reply/weather/current_conditions/temp_f/@data

may do the trick.

Sign up to request clarification or add additional context in comments.

Comments

0

Did you try this implementation?

http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

1 Comment

What does that really have to do with the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.