瞭解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' –