0

What I would like to do is access the yahoo weather xml from the rss, and get the data specifically from the yweather:condition tag. I tried with

xdoc.Load("http://xml.weather.yahoo.com/forecastrss?p=MKXX0001&u=c");
XmlNode xNode = xdoc.DocumentElement.SelectSingleNode("yweather:condition"); 

But with no success. How can I access the xml from yahoo weather and get all the attributes there? Also, how can I save all the attributes to my local xml file?

user2962759
  • 59
  • 3
  • 13

2 Answers2

0

Your XPath is wrong

Expected XPath should be

/rss/channel/item/yweather:condition

Other things are, XPath contains prefix so you need to specify namespacemanager.

Your Code should be

XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://xml.weather.yahoo.com/forecastrss?p=MKXX0001&u=c");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
XmlNode xNode = xdoc.DocumentElement.SelectSingleNode("/rss/channel/item/yweather:condition", nsmgr);
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
  • then how can i save the data to my local document xdoc2.Load("data.xml")? – user2962759 Feb 08 '14 at 10:23
  • @user2962759: You can save the xml from xdoc using OuterXml property that is `xdoc.OuterXml`. To read all the attributes, you need to iterate through `xNode.Attributes` – Siva Charan Feb 08 '14 at 11:47
0

Learn XPath to know how to select every particular element of the xml. Yahoo weather xml has namespaces, so you'll need XmlNamespaceManager as second argument for SelectSingleNode method. This example demonstrate how to get all attributes from <yweather:condition> element :

var xdoc = new XmlDocument();
xdoc.Load("http://xml.weather.yahoo.com/forecastrss?p=MKXX0001&u=c");
var nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
var _attributes = xdoc.SelectSingleNode("/rss/channel/item/yweather:condition", nsmgr).Attributes;
foreach (XmlAttribute attr in _attributes)
{
    Console.WriteLine("Attribute: {0}, Value: {1}", attr.Name, attr.Value);
}
har07
  • 88,338
  • 12
  • 84
  • 137