您的位置:首页 > 运维架构 > 网站架构

你的网站被订阅了吗(浅谈RSS2.0)续

2008-06-14 17:21 309 查看
继上一篇 你的网站被人订阅了吗?(浅谈Rss2.0)

通过这篇文章你可以了解到:

1.对Rss的创建有一个更好的方法

2.创建一个多版本的可订阅源

在这里感谢紫色永恒

为我们介绍了MS给我们提供的这么好的工具 (此工具被包含在System.ServiceModel.Syndication空间下,需.net3.X支持)

下面我们来实现生成一个RSS源:

我们新建一个asp.net 3.5的网站

创建一个一般应用程序文件(Handler.ashx)

代码如下:

<%@ WebHandler Language="C#" Class="Handler" %>

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {

context.Response.ContentType = "text/xml";

准备RSS源中的内容项#region 准备RSS源中的内容项

SyndicationItem item1 = new SyndicationItem("博客内容1标题", "博客内容1内容", new Uri("http://leleroyn.cnblogs.com"));

item1.PublishDate = new DateTimeOffset(DateTime.Parse("2008-6-11 12:23:24"));

item1.Authors.Add(new SyndicationPerson("leleroyn@gmail.com", "Ants", string.Empty));

SyndicationItem item2 = new SyndicationItem("博客内容2标题", "博客内容2内容", new Uri("http://leleroyn.cnblogs.com"));

item2.PublishDate = new DateTimeOffset(DateTime.Parse("2008-6-12 12:23:24"));

item2.Authors.Add(new SyndicationPerson("leleroyn@gmail.com", "Ants", string.Empty));

SyndicationItem item3 = new SyndicationItem("博客内容3标题", "博客内容3内容", new Uri("http://leleroyn.cnblogs.com"));

item3.PublishDate = new DateTimeOffset(DateTime.Parse("2008-6-10 12:23:24"));

item3.Authors.Add(new SyndicationPerson("leleroyn@gmail.com","Ants",string.Empty));

List<SyndicationItem> items = new List<SyndicationItem>();

items.Add(item1);

items.Add(item2);

items.Add(item3);

#endregion

创建一个RSS对象#region 创建一个RSS对象

SyndicationFeed rs = new SyndicationFeed("Ants的博客", "博客宣言:一起学习,同时向上!", new Uri("http://leleroyn.cnblogs.com"), items);

rs.Copyright = new TextSyndicationContent("copyright 2008 Ants");

Rss20FeedFormatter rss20 = rs.GetRss20Formatter();//创建RSS2.0源

// Atom10FeedFormatter atom = rs.GetAtom10Formatter();//创建Atom源

#endregion

输出源#region 输出源

System.Text.StringBuilder sb = new System.Text.StringBuilder();

XmlWriterSettings xs = new XmlWriterSettings();

xs.Encoding = System.Text.Encoding.UTF8;

XmlWriter xm = XmlWriter.Create(sb, xs);

rss20.WriteTo(xm);

// atom.WriteTo(xm);

xm.Close();

string str = sb.ToString().Replace("utf-16", "utf-8");//注意这个地方,此地方花了我好多时间,默认居然为utf-16格式,晕啦

context.Response.Write(str); //输出到浏览器

#endregion

}

public bool IsReusable {

get {

return false;

}

}

}

直接运行就行啊,

至于如何用这个API来获取源,里面也有相应的方法,大家有兴趣就自己试试,我就不演示啦

如果你的项目没有用上.net 3.x,可以参照我的上一篇文章:

你的网站被人订阅了吗?(浅谈Rss2.0)

希望对大家有帮助,再次献丑啦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: