2012-05-08 48 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); 
    } 

}