【问题标题】:Google Weather API conditions谷歌天气 API 条件
【发布时间】:2012-05-17 03:01:55
【问题描述】:

我正在使用 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=Boston+MA

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

是否可以根据 XML 文件中的内容对 xml 进行一些检查,以便仅提取当前的数据?

谢谢!

【问题讨论】:

标签: java api weather weather-api google-weather-api


【解决方案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); 
  }

}

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 2011-07-29
    • 1970-01-01
    • 2011-06-25
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    相关资源
    最近更新 更多