0

SAX を使用して 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=ボストン+マサチューセッツ州

その間、私は現在の日付のみの条件を取得しようとしています。将来の日付ではありません。

XML ファイルの内容に基づいて現在のデータのみをプルするために、xml に入れることができるチェックはありますか?

ありがとう!

4

1 に答える 1

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

}
于 2012-05-08T16:29:39.510 に答える