I recently received an email from a reader who asked how to read the weather from a Yahoo feed. I’ve posted the code here in case it’s of any use to anyone else.
protected void Page_Load(object sender, EventArgs e)
{
//GS - Clear all headers written already
Response.Clear();
//GS - Fetch the weather information
string uri =
@"http://xml.weather.yahoo.com/forecastrss?p=UKXX0025&u=c";
XPathDocument xpd = null;
try
{
xpd = new XPathDocument(uri);
}
catch (XmlException xe)
{
Response.Write("The following xml error occurred: " +
xe.Message);
Response.End();
return;
}
//GS - Create a navigator
XPathNavigator xpn = xpd.CreateNavigator();
//GS - Pull out the weather information from the xml
string weather = "";
try
{
XPathNavigator node =
xpn.SelectSingleNode(@"/rss/channel/item/description");
weather = HttpUtility.HtmlDecode(node.InnerXml);
}
catch (XPathException xpe)
{
Response.Write("The following XPath exception occurred: "
+ xpe.Message);
Response.End();
return;
}
//GS - Write out the weather information
Response.Write("<html>");
Response.Write("<body>");
Response.Write(weather);
Response.Write("</body>");
Response.Write("</html>");
}
Tags: Yahoo, Weather, Asp.Net, C#