了解XPath来知道如何选择XML的每一个特定的元素。雅虎天气xml有命名空间,因此您需要XmlNamespaceManager
作为SelectSingleNode
方法的第二个参数。此示例演示如何从<yweather:condition>
元素获取所有属性:
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);
}
然后如何将数据保存到本地文档xdoc2.Load(“data.xml”)? – user2962759
@ user2962759:您可以使用“xdoc.OuterXml”的OuterXml属性从xdoc保存xml。要读取所有属性,您需要遍历'xNode.Attributes' –