javaapiweatherweather-apigoogle-weather-api

Google Weather API conditions


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!


Solution

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