试图从BBC阅读RSS Feed

时间:2015-01-01 11:19:29

标签: c#

我正在尝试从BBC解析RSS提要,但它什么也没有返回! RSS Feed

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();

1 个答案:

答案 0 :(得分:2)

您正在寻找没有名称空间的元素。来自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="..."属性为后代元素(以及那个元素)指定默认命名空间。

所以你想要:

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();

请注意我在这里删除了查询表达式,只是使用了方法调用 - 如果查询只是“从x选择y”,那么查询表达式只会增加伪装。

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

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