ASP.NET 生成 RSS Feed

前段时间在写RSS Feed。
经过了几次的修改,把相关的代码写成了单独的类。
感觉重用时还算比较方便的。于是贴出来,大家一起研究研究。

以下是RssBase.cs类:


  1using System;
  2using System.Collections.Generic;
  3using System.Xml;
  4
  5namespace MyMedia.Utilities
  6{
  7    public class RssBase
  8    {
  9        RssBase constructor
 21
 22        [Serializable]
 23        public sealed class ItemInfo
 24        {
 25            ItemInfo constructor
 55
 56            Internal item variables
 74
 75            Item properties
147
148        }

149
150        Const string
166
167        Internal member variables
172
173        Properties
191
192        Private method
326
327        /// <summary>
328        /// Write RSS feed
329        /// </summary>

330        public void WriteRSS()
331        {
332            WritePrologue();
333            foreach (ItemInfo info in items)
334            {
335                WriteItem(info);
336                if (hasMedia)
337                    WriteItemMedia(info);
338                WriteItemEnd();
339            }

340            WriteEnd();
341        }

342    }

343}

然后使用一个FeedBase.cs类,调用上面的RssBase类中的方法和属性。代码如下。(该文件有改动,如要编译,需做相关修改)

 1using System.Collections.Generic;
 2using System.Configuration;
 3using System.Data;
 4using System.Text;
 5using System.Web;
 6using System.Web.UI;
 7using System.Xml;
 8
 9
10public class FeedBase : Page
11{
12    public void GenerateRss()
13    {
14
15        IList<RssBase.ItemInfo> items = new List<RssBase.ItemInfo>();
16
17        // Populate items. 
18        foreach (DataRow row in rows)
19        {
20            RssBase.ItemInfo item = new RssBase.ItemInfo(row["Title"].ToString(), "link", row["Description"].ToString(), row["PubDate"].ToString(), row["Author"].ToString(), "guid");
21            items.Add(item);
22        }

23
24        XmlTextWriter xmlWriter = new XmlTextWriter(Response.OutputStream,
25            Encoding.UTF8);
26
27        RssBase rssBase = new RssBase(xmlWriter, false, items);
28        rssBase.WriteRSS();
29
30        xmlWriter.Flush();
31        xmlWriter.Close();
32
33        Response.ContentEncoding = Encoding.UTF8;
34        Response.ContentType = "text/xml";
35        Response.Cache.SetCacheability(HttpCacheability.Public);
36
37        Response.End();
38    }

39
40}

41
42

最后,只要新建一个feed.aspx文件,继承FeedBase类,调用该类中的GenerateRss()方法就可以轻松生成你所期望的RSS Feed :)
posted @ 2007-02-08 11:46  dail  阅读(409)  评论(0编辑  收藏  举报