RSS全称Really Simple Syndication。一些更新频率较高的网站可以通过RSS让订阅者快速获取更新信息。RSS文档需遵守XML规范的,其中必需包含标题、链接、描述信息,还可以包含发布时间、最后更新时间等信息。
本文将介绍通过LINQ to XML生成XML文档,并在ASP.NET MVC Web应用程序中输出。
在生成RSS文档前,先简单了解一下RSS的结构。根节点rss下有channel节点,channel节点的一些子节点(title,link,description)包含了该RSS的部分描述信息。channel下可包含多个item节点用来表示多个内容信息,如博客中的文章、论坛中的帖子。


2 < channel >
3 < title > channel标题 </ title >
4 < link > 网页地址 </ link >
5 < description > channel描述 </ description >
6 < item >
7 < title > 内容1标题 </ title >
8 < description > 内容1描述 </ description >
9 < link > 内容1链接 </ link >
10 </ item >
11 < item >
12 < title > 内容2标题 </ title >
13 < description > 内容2描述 </ description >
14 < link > 内容2链接 </ link > </ item >
15 </ channel >
16 </ rss >
1. 用LINQ to XML生成类似上述的文档。
1.1 新建一个XDocument,添加根节点和相关属性描述。


2 new XDeclaration( " 1.0 " , " utf-8 " , " yes " ), // XML文档声明
3 new XElement( " rss " , // 根节点
4 new XAttribute( " version " , " 2.0 " ), // rss节点的属性
5 new XElement(channel // rss的子节点channel
6 ))); )));
1.2 处理channel节点和它的相关描述。


2 channel.Add( new XElement[]{
3 new XElement( " title " , " Test " ), // channel标题
4 new XElement( " link " , " http://localhost " ), // 页面链接
5 new XElement( " description " , " Test RSS " ) // channel描述
6 });
1.3 往channel节点增加内容信息,rssFeedList是 List<RssFeed>类型的。由于item数量不固定,这里用了foreach将list中的每一个内容信息都加到channel。


2 {
3 XElement item = new XElement( " item " , new XElement[]{ // 生成一个新的item节点
4 new XElement( " title " ,rssFeed.Title), // 为新的item节点添加子节点
5 new XElement( " description " ,rssFeed.Description),
6 new XElement( " link " ,rssFeed.Link),
7 new XElement( " pubDate " ,rssFeed.PublishDate)
8 });
9 channel.Add(item); // 将新的item节点添加到channel中
10 }
2. 创建RssFeedResult类
我们写一个RssFeedResult类,继承自ActionResult,以便在ASP.NET MVC的controller中返回RSS。关于这部分内容可参考之前的一篇文章《让ASP.NET MVC页面返回不同类型的内容》。


2 {
3 List < RssFeed > Data { get ; set ; }
4
5 public RssFeedResult(List < RssFeed > data)
6 {
7 Data = data;
8 }
9
10 public override void ExecuteResult(ControllerContext context)
11 {
12 if (context == null )
13 {
14 throw new ArgumentNullException( " context " );
15 }
16
17 HttpResponseBase response = context.HttpContext.Response;
18 response.ContentType = " text/xml " ; // 设置HTTP头中的ContentType
19 XDocument result = RssFeedHelper.GetRssFeed(Data); // 获取XML数据
20 response.Write(result.ToString()); // 将XML数据写入response中
21 }
22 }
3. 在controller中使用
我们只要在controller中调用RssFeedResult(rssFeedList)方法即可返回RSS页面了。


{
// 添加2个测试用的数据
RssFeed r1 = new RssFeed { Description = " Test1 " , Link = " http://localhost/1 " , Title = " Test1 " , PublishDate = DateTime.Now };
RssFeed r2 = new RssFeed { Description = " Test2 " , Link = " http://localhost/2 " , Title = " Test2 " , PublishDate = DateTime.Now };
List < RssFeed > rssFeedList = new List < RssFeed > ();
rssFeedList.Add(r1);
rssFeedList.Add(r2);
// 返回RSS
return new RssFeedResult(rssFeedList);
}
示例下载 (Visual Studio 2010)
另外,还有一个工具ASP.NET RSS Toolkit,有需要的可以参考一下。