尝试阅读来自 BBC 的 RSS 提要

trying to read RSS Feed from BBC

我正在尝试解析来自 BBC 的 RSS 提要,但 return 什么都没有! RSS 订阅

http://www.bbc.co.uk/arabic/middleeast/index.xml

我的代码

var item = (from descendant in document.Descendants("entry")
                           select new NewsItem()
                           {
                               link = descendant.Element("link").Attribute("href").Value,
                               description = descendant.Element("summary").Value,
                               title = descendant.Element("title").Value,
                               image = " " // entry > link > img media:content > second media:thumbnail > url attribute
                               entry_date = DateTime.Now,
                               category = " " // second descendant.Elements("category") > label
                           }).ToList();

您正在寻找没有命名空间的元素。来自 RSS 提要的根元素:

<feed xmlns="http://www.w3.org/2005/Atom"
      xmlns:media="http://search.yahoo.com/mrss/"
      xmlns:dc="http://purl.org/dc/elements/1.1/"
      xmlns:dcterms="http://purl.org/dc/terms/">

xmlns="..." 属性为后代元素(以及那个元素)指定 default 命名空间。

所以你想要:

XNamespace ns = "http://www.w3.org/2005/Atom";
var item = document.Descendants(ns + "entry")
                   .Select(entry => new NewsItem
                           {
                               link = entry.Element(ns + "link")
                                           .Attribute("href").Value,
                               description = entry.Element(ns + "summary").Value,
                               title = entry.Element(ns + "title").Value,
                               image = " "
                               entry_date = DateTime.Now,
                               category = " "
                           })
                   .ToList();

请注意我是如何在此处删除查询表达式的,只是使用方法调用 - 如果查询只是 "from x select y",那么查询表达式只会添加 cruft。

此外,我强烈建议您开始遵循 .NET 命名约定(例如 EntryDate 而不是 entry_date - 尽管该示例的值也不正确...)。

编辑:如评论中所述,您还可以使用 SyndicationFeed 或第三方库来解析提要。您不是第一个想在 .NET 中解析 RSS 的人:)