代码改变世界

.Net3.5创建RSS

2010-08-10 10:27  空逸云  阅读(276)  评论(0编辑  收藏  举报

在之前,创建RSS必须要手动调用XML API生成XML,LINQ to XML的出现大大减少了工作量(可参考LINQ构建RSS).然而.在.Net3.5中.微软提供了更方便快捷的API.详见System.ServiceModel.Syndicatio命名空间但是.我们使用到的只有 SyndicationFeed 类,SyndicationItem 类 ,Rss20FeedFormatter 类. RSS的标准协议还是比较杂的.对于这方面不甚了解的同学.可以参考关于 Blog 和 RSS 的全面介绍 .

首先.我们看一段RSS示例


<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
<channel>
  
<title>博客园-空逸云</title> 
  
<link>http://www.cnblogs.com/kongyiyun/</link> 
  
<description>路漫漫其修远兮,吾将上下而求索.</description> 
  
<language>zh-cn</language> 
  
<lastBuildDate>Tue, 10 Aug 2010 02:00:54 GMT</lastBuildDate> 
  
<pubDate>Tue, 10 Aug 2010 02:00:54 GMT</pubDate> 
  
<ttl>60</ttl> 
<item>
  
<title>星级评分公式</title> 
  
<link>http://www.cnblogs.com/kongyiyun/archive/2010/08/06/1794441.html</link> 
  
<dc:creator>空逸云</dc:creator> 
  
<author>空逸云</author> 
  
<pubDate>Fri, 06 Aug 2010 13:31:00 GMT</pubDate> 
  
<guid>http://www.cnblogs.com/kongyiyun/archive/2010/08/06/1794441.html</guid> 
<description>
<![CDATA[ <p>作者: <a href="http://www.cnblogs.com/kongyiyun/" target="_blank">空逸云</a> 发表于 2010-08-06 21:31 <a href="http://www.cnblogs.com/kongyiyun/archive/2010/08/06/1794441.html" target="_blank">原文链接</a> 阅读: 6 评论: 0</p>.....
  
]]> 
  
</description>
  
</item>
</channel>
  
</rss>

 

 

再比较MSDN.不难发现.必要有一个channel节.其中包含有title,link,description等属性.再下.每个item就是我们所要呈现的重要内容.在这里.重点就是SyndicationFeed 类和SyndicationItem.我的实现如下.

首先建立了一个RssBuilder类.用于创建必要的SyndicationFeed.

  /// <summary>

    /// Rss构建器
    
/// </summary>
    public class RssBuilder
    {
        
private int itemAmount = ACookContext.Current.ACookSettingsConfig.RssAmount;
        
private int _userId = 0;

        
public RssBuilder() { }

        
public RssBuilder(int userId) { _userId = userId; }

        
public SyndicationFeed BuildRss()
        {
            var recipes 
= GetSources();

            var ctx 
= ACookContext.Current;
            
string feedTitle = string.Format("{0} {1}'s Rss", ctx.ACookSettingsConfig.SiteName, _userId == 0 ? string.Empty : ctx.ACookAppConfig.Author);
            
string targetUrl = string.Format("{0}/{1}", ctx.ACookSettingsConfig.DomainName, ctx.ACookAppConfig.Application);

            SyndicationFeed feed 
= new SyndicationFeed(feedTitle, "ACook's Rss"new Uri(targetUrl), "What's this?", DateTime.Now)
            {
                Language 
= "zh-cn"
            };
            List
<SyndicationItem> items = new List<SyndicationItem>();
            
foreach (var x in recipes)
            {
                SyndicationItem item 
= new SyndicationItem(x.RecipeTitle, x.CookSteps, new Uri(string.Format("http://www.acook.cc/recipe/{0}.aspx", x.RecipeId)), x.RecipeSample, x.PTime);
                item.Categories.Add(
new SyndicationCategory(x.Category.CategoryTitle));
                item.Authors.Add(
new SyndicationPerson(x.Publisher.Author));
                items.Add(item);
            }
            feed.Items 
= items;
            
return feed;
        }

        
private string BuildContent(ACookRecipe recipe)
        {
            
//TODO:生成页面的呈现内容
            return recipe.CookSteps;
        }

        
private IEnumerable<ACookRecipe> GetSources()
        {
           
//TODO:获取数据源,
        }

    }

然后.再创建一个Rss.cs IHttpHandler类.此处要引用System.ServiceModel.Web程序集,用户呈现RSS内容实现如下.


public void ProcessRequest(HttpContext context)
        {
            RssBuilder builder 
= new RssBuilder(ACookContext.Current.ACookAppConfig.UserId);
            var feed 
= builder.BuildRss();
            context.Response.ContentType 
= "text/xml";
            Rss20FeedFormatter rssfm 
= new Rss20FeedFormatter(feed);
            XmlWriter rssWriter 
= new XmlTextWriter(context.Response.OutputStream, System.Text.Encoding.UTF8);
            rssfm.WriteTo(rssWriter);
            rssWriter.Close();
        }

 

 

由于是要呈现于页面当中.我们就是用了Response.OutputStream,如果是写入XML文件中.可以可以XmlWriter.Create("rss.xml");

最后.再在WebConfig的HttpHandlers节中加入

 add verb="*" path="rss.rss" type="ACook.FrameWork.Handler.Rss,ACook.FrameWork"/>

 即可.

好了.现在我们来访问我们创建的RSS吧.