Rad
Rad

Reputation: 830

How to get data from an URL xml-file?

I'm making an android app - where I need to have weather-information. I've found this from yahoo weather. It's an XML and I want information such as: "day", "low" and "high".

Refer: 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"/>

(Line can be found in the bottom of the link)

I have no idea how to do this - please help. Source codes, examples and clues will be appreciated.

Upvotes: 0

Views: 8416

Answers (3)

Rad
Rad

Reputation: 830

Here's the solution for future users:

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

Upvotes: 4

Nishant
Nishant

Reputation: 55856

The link seems to be a feed. (which is XML, obviously). There are many feed-reader APIs in Java. So, here you go

  1. Read feed documentation, http://developer.yahoo.com/weather/
  2. Read how to parse/read the feed, Rome Library to read feeds Java
  3. Pull out your desired fields.

I guess this is already done. (easily found on Google) http://www.javahouse.altervista.org/gambino/Articolo_lettura_feed_da_java_en.html

Upvotes: 0

Josh
Josh

Reputation: 111

It's been a couple of years since I used XML in Android, but this was quite helpful to me when I started out: anddev.org

Upvotes: 0

Related Questions