2012-05-08 19 views
0

SAXを使用してGoogle天気APIから情報を取得していますが、「条件」に問題があります。Google天気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

** 2012年にGoogle天気APIがシャットダウン** - > 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); 
    } 

}