2012-05-08 41 views
0

我正在使用SAX从Google天气API中获取信息,并且遇到了“条件”问题。Google Weather API条件

具体来说,我正在使用此代码:

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

要东西拉这样的XML:

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

同时我试图让条件仅当天,而不是将来的任何日子。

是否有一些检查我可以放入xml中以仅根据XML文件中的内容为当前提取数据?

谢谢!

+0

¿您是否需要使用SAX?这是完全可能的,但这看起来像一个XPath工作? –

+0

萨克斯似乎是解析这个最简单的方法。尽管如此,我仍然在学习新的方式。 –

+0

** Google天气API在2012年被关闭** - > http://stackoverflow.com/questions/12145820/google-weather-api-gone/35943521 –

回答

1

这应该可以做到。请记住,如果您使用的是框架,那么它可能具有用于XPath的实用程序函数,以使其更简单。

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

}