我正在尝试从 http://itunes.apple.com/us/rss/topsongs/limit=10/genre=2/xml 中读取 XML 提要.
我想像这样访问字段:
<im:price amount="1.29000" currency="USD">$1.29</im:price>
<im:releaseDate label="December 31, 1960">1960-12-31T16:00:00-07:00</im:releaseDate>
这是我到目前为止所做的:
var xml = "http://itunes.apple.com/us/rss/topsongs/limit=10/genre=2/xml";
XmlDocument doc = new XmlDocument();
doc.Load(xml);
XmlNodeList items = doc.SelectNodes("//entry");
foreach (var item in items) {
// Do something with item.
}
不过运气不好。 items
为空。为什么?我做错了什么?
最佳答案
您需要创建命名空间管理器以将 RSS 和 iTunes 自定义标签命名空间 URI 映射到短前缀(下例中的 itunes 和 im):
var xml = "http://itunes.apple.com/us/rss/topsongs/limit=10/genre=2/xml";
XmlDocument doc = new XmlDocument();
doc.Load(xml);
var namespaceManager = new XmlNamespaceManager(doc.NameTable);
namespaceManager.AddNamespace("itunes", "http://www.w3.org/2005/Atom");
namespaceManager.AddNamespace("im", "http://itunes.apple.com/rss");
XmlNodeList items = doc.SelectNodes("//itunes:entry", namespaceManager);
foreach (XmlNode item in items)
{
var price = item.SelectSingleNode("im:price", namespaceManager);
var releaseDate = item.SelectSingleNode("im:releaseDate", namespaceManager);
if (price != null)
{
Console.WriteLine(price.Attributes["amount"].InnerText);
}
if (releaseDate != null)
{
Console.WriteLine(releaseDate.Attributes["label"].InnerText);
}
}
对于该特定提要,您应该获得 10 个条目。
它在 docs as well 中:
If the XPath expression does not include a prefix, it is assumed that the namespace URI is the empty namespace. If your XML includes a default namespace, you must still use the XmlNamespaceManager and add a prefix and namespace URI to it; otherwise, you will not get any nodes selected. For more information, see Select Nodes Using XPath Navigation.
或者,您可以使用与 namespace 无关的 XPath(来自 here):
XmlNodeList items = doc.SelectNodes("//*[local-name() = 'entry']");
最后,不确定您为什么说 items 为 null。它不可能是。运行原始代码时,您应该得到:
关于c# - 无法读取 iTunes XML 提要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25132128/