2012-02-19 136 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