簡體   English   中英

Google Weather API條件

[英]Google Weather API conditions

我正在使用SAX從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=波士頓+ MA

同時,我正在嘗試僅獲取當前日期的條件,而不希望獲取將來的任何日期的條件。

是否有一些檢查可以放入xml中,以便僅根據XML文件中的內容提取當前數據?

謝謝!

這應該可以解決問題。 請記住,如果您使用的是框架,它可能具有實用工具功能來簡化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); 
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM