0

I'm using SAX to pull information from the google weather API and I'm having issues with the "conditions".

Specifically I'm using this code:

public void startElement (String uri, String name, String qName, Attributes atts) {
    if (qName.compareTo("condition") == 0) {
        String cCond = atts.getValue(0);
        System.out.println("Current Conditions: " + cCond);
        currentConditions.add(cCond);
    }

To pull XML from something like this:

http://www.google.com/ig/api?weather=Boston+MA

Meanwhile I'm trying to get conditions only for the current day, and not for any days in the future.

Is there some check I could put into the xml to only pull data for the present day based on what's in the XML file?

Thanks!

John Slegers
  • 45,213
  • 22
  • 199
  • 169
A_Elric
  • 3,508
  • 13
  • 52
  • 85

1 Answers1

1

This should do the trick. Keep in mind that if your are using a framework it might have utility functions for XPath to make it simpler.

import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;

public class XPathWeather {

  public static void main(String[] args) 
   throws ParserConfigurationException, SAXException, 
          IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("/tmp/weather.xml");

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("/xml_api_reply/weather/current_conditions/condition/@data");

    String result = (String) expr.evaluate(doc, XPathConstants.STRING);
    System.out.println(result); 
  }

}
Víctor Romero
  • 5,107
  • 2
  • 22
  • 32