RSS正在改变着人们的阅读习惯,一时间大部份网站都支持了RSS输出。本人小站(www.web2bar.cn)当然也不能落后。自己写了用asp.net生成RSS2.0标准文件的方法。我用的是文件流方法,话不多说,看下面代码:
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?><?xml-stylesheet type=\"text/xsl\" href=\"/Styles/WebBarRss.xslt\"?>");
sb.Append(System.Environment.NewLine);
sb.Append("<rss version=\"2.0\">");
sb.Append(System.Environment.NewLine);
sb.Append(" <channel>");
sb.Append(System.Environment.NewLine);
sb.Append(" <title>" + title + "</title>");
sb.Append(System.Environment.NewLine);
sb.Append(" <link>http://www.web2bar.cn</link>");
sb.Append(System.Environment.NewLine);
sb.Append(" <description>" + title + "</description>");
sb.Append(System.Environment.NewLine);
WebBar.BLL.BArticle bArticle = new WebBar.BLL.BArticle();
IList<ArticleEntity> ArticleEntitys = bArticle.List(int.Parse(ddlRssCount.SelectedValue.ToString()), int.Parse(ddlChannelID.SelectedValue.ToString()));
foreach (ArticleEntity ae in ArticleEntitys)
{
sb.Append(" <item>");
sb.Append(System.Environment.NewLine);
sb.Append(" <title><![CDATA["+ae.ArticleTitle+"]]></title>");
sb.Append(System.Environment.NewLine);
sb.Append(" <link>http://www.web2bar.cn/Article/" + ae.ArticleID.ToString() + ".aspx</link>");
sb.Append(System.Environment.NewLine);
sb.Append(" <description><![CDATA["+ae.Description+"]]></description>");
sb.Append(System.Environment.NewLine);
sb.Append(" <author>"+ae.ArticleAuthor+"</author>");
sb.Append(System.Environment.NewLine);
sb.Append(" <pubDate>"+ae.ArticleCreateTime.ToString("yyyy-MM-dd HH:mm")+"</pubDate>");
sb.Append(System.Environment.NewLine);
sb.Append(" <comments>" + ae.CommentCount.ToString() + "</comments>");
sb.Append(System.Environment.NewLine);
sb.Append(" </item>");
sb.Append(System.Environment.NewLine);
}
sb.Append(" </channel>");
sb.Append(System.Environment.NewLine);
sb.Append("</rss>");
try
{
using (FileStream fs = new FileStream(Server.MapPath(xmlFileName), FileMode.Create, FileAccess.Write, FileShare.Write))
{
using (StreamWriter streamwriter = new StreamWriter(fs, Response.ContentEncoding))
{
streamwriter.Write(sb);
Common.JsUtility.Alert("成功生成RSS聚合内容");
}
}
}
生成的XML文件格式如下:http://www.web2bar.cn/XML/WebBarRss.xml

