LINQ to RSS






4.45/5 (8投票s)
RSS 中的语言集成查询。
引言
RSS 代表“Really Simple Syndication”(极简聚合)。RSS 是一种网络信息源,允许我们发布任何类型的频繁更新数据,例如新闻、博客等。
LINQ 是一种很棒的查询技术,因为它与数据源无关。因此,我开始开发 LINQ to RSS,这是一个简单的库,可以简化对 RSS 文档的查询。
背景
RSS 是一种基于 XML 的文档,包含特定频道的订阅源,其扩展名为 .rss 或 .xml。
<rss version="2.0">
<channel>
<title>News Headlines</title>
<link>http://www.myWebsite.com/</link>
<description>News Website.</description>
<lastBuildDate>Mon, 06 Sep 2010 00:01:00</lastBuildDate>
<pubDate>2009-01-01</pubDate>
<item>
<title>Title1</title>
<link>http://www.myWebsite.com/news/4371</link>
<description>
some description goes here.
</description>
<guid>4f71539d-0341-4545-b2b8-90cd13562d4e</guid>
<pubDate>2010-01-23</pubDate>
</item>
<item>
<title>Space Exploration</title>
<link>http://www.myWebsite.com/news/4372</link>
<description>
some description goes here.
</description>
<guid>cd13590c-45c4-ae76-abbb1-3e3effffa12e</guid>
<pubDate>2010-01-27</pubDate>
</item>
</channel>
</rss>
从上面的文件中可以看出,每个 RSS 文件都包含一个 channel 标签,其中包含有关提供订阅源的当前频道的描述性信息,在其下方是 item 标签,代表订阅源本身。每个 item 包含有关特定 item 的描述性信息,例如标题、链接等。
LINQ 本身并没有什么神奇之处……只要你拥有任何类型的数据源,例如 XML、数据库、注册表等。如果你将它表示为对象,那么 LINQ 就会负责其他事情,最初有 Lambda 表达式、扩展方法等等,使 LINQ 更容易查询这些对象。
Using the Code
在代码背后,重要的是 RSSDataContext
类,这是一个非常简单的类,包含有关 RSS 文档的描述:Channel、Feeds。
Public Class RssDataContext
Public Sub New(ByVal Path As String)
Dim doc As XDocument = XDocument.Load(Path)
Feeds = From item In doc.Element("rss").Element("channel").Elements("item")
Select New Feed With {.Title = item.Element("title").Value, _
.Link = item.Element("link").Value, _
.Description = item.Element("description").Value, _
.PublicationDate = item.Element("pubDate").Value, _
.GUID = Guid.Parse(item.Element("guid").Value)}
Channel = New Channel() With {.Title = doc...<title>.Value, _
.Link = doc...<link>.Value, _
.Description = doc...<description>.Value, _
.PublicationDate = doc...<pubDate>.Value, _
.LastBuildDate = doc...<lastBuildDate>.Value}
End Sub
Public Property Feeds As IEnumerable(Of Feed)
Public Property Channel As Channel
End Class
Feed
类只不过是一段代码,代表 RSS 文档中的每个订阅源
Public Class Feed
Property Title As String
Property Link As String
Property Description As String
Property PublicationDate As DateTime
Property GUID As Guid
End Class
以及 channel 类
Public Class Channel
Property Title As String
Property Link As String
Property Description As String
Property PublicationDate As DateTime
Property LastBuildDate As DateTime
End Class
现在我们可以这样使用它
Dim db As New RssDataContext("rss.xml")
Dim feeds = From f In db.Feeds
Select f
Console.WriteLine(db.Channel.Title)
Console.WriteLine(db.Channel.Link)
Console.WriteLine(db.Channel.Description)
Console.WriteLine(db.Channel.PublicationDate)
Console.WriteLine(db.Channel.LastBuildDate)
Console.WriteLine()
For Each f As Feed In feeds
Console.WriteLine(f.Title)
Next
我认为很棒的是,当有人想要使用强类型查询 RSS 文档,而不是处理 XML 时,无需花费大量时间学习 XML 编程,才能从 RSS 中获取任何信息。只需尝试我的代码,希望你喜欢。
关注点
- 开发 RSS 聚合器(阅读器)
- 在你的 Web 应用程序中显示一堆网络订阅源(RSS 订阅源模块)
历史
- LinqToRss 版本 1.0,其中包含查询 RSS 文档的基本功能