星期一, 10月 01, 2007

Google Weather API

Animaonline's Nerdy Corner: Google Weather API

This is a little guide on how to use the Google Weather API

Use this XML file for output in Fahrenheit:
http://www.google.com/ig/api?weather=Drammen //華氏 (ex. Taipei)
And this one for Celsius:
http://www.google.co.uk/ig/api?weather=Drammen //攝氏 (ex. Taipei)

And here is the sample C# parser (Celsius Version):using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;

///Code by Roman Alifanov - API by Google
///Posted on http://animaonline.blogspot.com
namespace GoogleWeatherAPI_Parser
{
class Program
{
static void Main(string[] args)
{
int i = 0;

//SelectNodes("xml_api_reply/weather/current_conditions")
//↑其中字串為指定哪個node,參考回傳的xml即可瞭解
XmlNodeList GWP_NodeList = GoogleWeatherAPI_Parser(@"http://www.google.co.uk/ig/api?weather=Drammen").SelectNodes("xml_api_reply/weather/current_conditions");
Console.WriteLine("Current weather in Drammen: " + GWP_NodeList.Item(i).SelectSingleNode("temp_c").Attributes["data"].InnerText);
Console.ReadLine();
}
private static XmlDocument GoogleWeatherAPI_Parser(string baseUrl)
{
HttpWebRequest GWP_Request;
HttpWebResponse GWP_Response = null;
XmlDocument GWP_XMLdoc = null;
try
{
GWP_Request = (HttpWebRequest)WebRequest.Create(string.Format(baseUrl));
GWP_Request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4";
GWP_Response = (HttpWebResponse)GWP_Request.GetResponse();
GWP_XMLdoc = new XmlDocument();
GWP_XMLdoc.Load(GWP_Response.GetResponseStream());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
GWP_Response.Close();
return GWP_XMLdoc;
}
}

沒有留言: