【问题标题】:Parsing iTunes Podcast XML in C# using System.Xml使用 System.Xml 在 C# 中解析 iTunes Podcast XML
【发布时间】:2014-11-09 02:53:51
【问题描述】:

我正在尝试用 C# 解析 iTunes 播客 XML 提要,但遇到了问题。它成功下载提要并将其放入 XmlDocument 对象(已测试)。之后,它进入 for-each 行,但永远不会进入循环。我不知道为什么它说频道/项目中没有任何元素(至少这是我此时的想法)。代码如下:

    string _returnedXMLData;
    XmlDocument _podcastXmlData = new XmlDocument();

    public List<PodcastItem> PodcastItemsList = new List<PodcastItem> ();

    _podcastXmlData.Load(@"http://thepointjax.com/Podcast/podcast.xml");

    string title = string.Empty;
    string subtitle = string.Empty;
    string author = string.Empty;

    foreach (XmlNode node in _podcastXmlData.SelectNodes(@"channel/item")) {
        title = node.SelectSingleNode (@"title").InnerText;
        subtitle = node.SelectSingleNode (@"itunes:subtitle").InnerText;
        author = node.SelectSingleNode (@"itunes:author").InnerText;
        PodcastItemsList.Add (new PodcastItem(title, subtitle, author));
    }
}

提前感谢您的帮助!非常感谢!

柯克兰

【问题讨论】:

  • 这里有什么不能使用 LINQ 的原因吗?

标签: c# .net xml podcast system.xml


【解决方案1】:

离开我的评论,我会使用XDocument

 var xml = XDocument.Load("http://thepointjax.com/Podcast/podcast.xml");

 XNamespace ns = "http://www.itunes.com/dtds/podcast-1.0.dtd";
 foreach (var item in xml.Descendants("item"))
 {
     var title = item.Element("title").Value;
     var subtitle = item.Element(ns + "subtitle").Value;
     var author = item.Element(ns + "author").Value;

     PodcastItemsList.Add (new PodcastItem(title, subtitle, author));
 }

itunes 是 XML 中的命名空间,因此您需要使用 XNamespace 来说明它。

【讨论】:

  • 工作就像一个魅力!非常感谢!
  • 与我尝试的方法相比,这种方法还有什么其他好处吗?您是否觉得在大多数情况下这是解析 XML 的最佳方式?你什么时候会用这个而不是另一个?对不起,我知道我听起来像一个问卷,但我真的很喜欢学习。任何回应将不胜感激!
  • Jon Skeet 给了a better answer 这个我可以提供给你。
【解决方案2】:

仅供参考,Apple 网站说 iTunes 命名空间链接区分大小写。我还没有使用 version="2.0" 部分,但到目前为止我还不需要它。我使用的是从其他地方复制的链接,即“...DTDs/Podcast-1.0.dtd”。只有将其更改为小写后,我的 RSS 阅读器中的解析才开始工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 2013-01-06
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多