c# - 无法读取 iTunes XML 提要

标签 c# xml rss itunes

我正在尝试从 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。它不可能是。运行原始代码时,您应该得到:

enter image description here

关于c# - 无法读取 iTunes XML 提要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25132128/

相关文章:

c# - Collection<T> 是封装 IList<T> 还是枚举 IList<T>?

java - XML 中的 UI 布局和元素

C# 使用关键字嵌套在单行中

java - 从节点选择中选择节点

java - 如何从android中的string.xml文件获取字符串资源

php - 我应该在 PHP 中使用什么 RSS 解析器?

Facebook 通知 RSS 提要

python - Django/Python 世界中是否有与 WordPress 的 SimplePie 插件等效的东西?

c# - 按顺序搜索缺失的数字

c# - 将 JSON 解析为 C# 对象,其中 "0"作为 JSON 字符串中的对象名称