2012-02-19 39 views
0

我正在製作一個android應用程序 - 我需要獲取天氣信息。我從雅虎天氣發現了這個。這是一個XML,我需要諸如「日」,「低」和「高」等信息。如何從URL xml文件中獲取數據?

參見:http://weather.yahooapis.com/forecastrss?w=12718298&u=c

<yweather:forecast day="Sun" date="19 Feb 2012" low="-2" high="3" text="Clear" code="31"/> 

(線可以在鏈接的底部)我不知道如何做到這一點 - 請幫助。源代碼,例子和線索將不勝感激。

+2

鬥你有* *任何與XML解析熟悉? – 2012-02-19 15:06:51

+0

當文件位於計算機上(在C#中)時,我對從簡單的XML文檔讀取數據有所瞭解。但就是這樣。 – Rad 2012-02-19 15:27:22

回答

4

下面是未來用戶的解決方案:

InputStream inputXml = null; 
    try 
    { 



      inputXml = new URL("http://weather.yahooapis.com/forecastrss?w=12718298&u=c").openConnection().getInputStream(); 



     DocumentBuilderFactory factory = DocumentBuilderFactory. 
             newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document doc = builder.parse(inputXml); 
     NodeList nodi = doc.getElementsByTagName("yweather:forecast"); 

     if (nodi.getLength() > 0) 
     { 


      Element nodo = (Element)nodi.item(0); 

      String strLow = nodo.getAttribute("low"); 
      Element nodo1 = (Element)nodi.item(0); 
      String strHigh = nodo1.getAttribute("high"); 
      System.out.println("Temperature low: " + strLow); 
      System.out.println("Temperature high: " + strHigh); 

     } 
    } 
    catch (Exception ex) 
    { 
     System.out.println(ex.getMessage()); 
    } 
    finally 
    { 
     try 
     { 
      if (inputXml != null) 
      inputXml.close(); 
     } 
     catch (IOException ex) 
     { 
      System.out.println(ex.getMessage()); 
     } 
    } 
} 
+0

只是想說一個主要的感謝這個優秀的代碼。爲我節省了大量的時間。你今天做了一件好事。 – jjj 2012-10-08 22:48:51

0

這是一個幾年,因爲我在Android中使用XML,但是這是相當有幫助的我,當我開始了:anddev.org

0

的鏈接似乎是一個飼料。 (顯然是XML)。 Java中有許多供稿閱讀器API。所以,在這裏你去

  1. 閱讀Feed文檔,http://developer.yahoo.com/weather/
  2. 瞭解如何解析/讀取的飼料,Rome Library to read feeds Java
  3. 拿出你需要的字段。

我想這已經完成了。 (很容易在谷歌找到)http://www.javahouse.altervista.org/gambino/Articolo_lettura_feed_da_java_en.html

+0

謝謝!我會嘗試閱讀這些鏈接,看看我是否理解它! – Rad 2012-02-19 15:16:58