Getting Weather Information from Yahoo Web Services in C#

I wrote an article sometime back on The CodeProject that dealt with Geolocation. I wrote this back in 2005 so I figured I would update my post here and add a new twist.

The new code still uses YAHOO’s web services, however this time I am writing it in LINQ and C#. So lets dive right in shall we? This is a simple console based program, you can re do it as a webapp or a forms program, but the concept is the same.
using System;
using System.Linq;
using System.Xml.Linq;

namespace YahooWeather
{
    class Program
    {
        public string appid { get; set; }

        public Program(string appid)
        {
            this.appid = appid;
        }
    }
}

It starts off as any program does with a basic namespace deceleration, as you can see there is one property called appid that gets set when you create an instence of this class.

        public string GetWoeid(string Zipcode)
        {
            string query = String.Format("http://where.yahooapis.com/v1/places.q('{0}')?appid={1}", Zipcode, this.appid);
            XDocument thisDoc = XDocument.Load(query);
            XNamespace ns = "http://where.yahooapis.com/v1/schema.rng";

            return (from i in thisDoc.Descendants(ns + "place") select i.Element(ns + "woeid").Value).First();
        }

This function loads up http://where.yahooapis.com/v1/ and grabs the XML stream with LINQ then returns the woeid. The woeid is a unique number that identifies your location

Next, we have to get the weather RSS feed from Yahoo using your woeid

        public void GetWeather(string Zipcode)
        {
            string query = String.Format("http://weather.yahooapis.com/forecastrss?w={0}", GetWoeid(Zipcode));
            XDocument thisDoc = XDocument.Load(query);
            XNamespace ns = "http://xml.weather.yahoo.com/ns/rss/1.0";
            var results = (from i in thisDoc.Descendants(ns + "forecast") select i);

            foreach (var thisResult in results)
                Console.WriteLine("{0}, it will be {1} with a low of {2} and a high of {3}", thisResult.Attribute("date").Value, thisResult.Attribute("text").Value, thisResult.Attribute("low").Value, thisResult.Attribute("high").Value);
        }

This function prints out the current weather conditions. In the same way we got the woeid (parsing xml/rss), we are getting the weather results. All thats left now is the main procedure.

        static void Main(string[] args)
        {
            Program thisYahoo = new Program("<strong>YOUR KEY HERE</strong>");

            Console.Write("Enter your zip code please: ");
            thisYahoo.GetWeather(Console.ReadLine());

            Console.Write("Press Enter...");
            Console.ReadLine();
        }

View the Yahoo GeoPlanet API documentation | View the Yahoo Weather API documentation | Get a Yahoo application ID

  Weather.zip (736 bytes, 342 hits)