用Asp.net生成RSS文件,以便Rss阅读器订阅(收藏的)

用Asp.net生成RSS文件,以便Rss阅读器订阅。

环境如下:
A:数据库环境:
    SQLServer2005(数据库实例:机器名+SQLServer2005)
B:开发环境
     Vs2005.net
数据库
Create table Tb_Test(ID  int identity(1,1),Title varchar(20), Description varchar(100), AddDate datetime default(getdate()))
go
insert into tb_test(Title,Description)
select '中国新闻','新华社网公司'
union all
select '中央新闻','中央电视台'
union all
select '国际新闻','国际广播'
union all
select '环球新闻','环球广播'
union all
select '凤凰新闻','凤凰卫视'
go

 Web.config
<?xml version="1.0"?>
<!--
    注意: 除了手动编辑此文件以外,您还可以使用
    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
     “网站”->“Asp.Net 配置”选项。
    设置和注释的完整列表在
    machine.config.comments 中,该文件通常位于
    WindowsMicrosoft.NetFrameworkv2.xConfig 中
-->
<configuration>
    <appSettings>
        <add key="Db_cfgConn" value="server=.SQLSERVER2005;database=Test_DB;uid=sa;pwd=ylwtsmt"/>
    </appSettings>
    <connectionStrings/>
    <system.web>
        <!--
            设置 compilation debug="true" 将调试符号插入
            已编译的页面中。但由于这会
            影响性能,因此只在开发过程中将此值
            设置为 true。
        -->
        <compilation debug="true"/>
        <!--
            通过 <authentication> 节可以配置 ASP.NET 使用的
            安全身份验证模式,
            以标识传入的用户。
        -->
        <authentication mode="Windows"/>
        <!--
            如果在执行请求的过程中出现未处理的错误,
            则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
            开发人员通过该节可以配置
            要显示的 html 错误页
            以代替错误堆栈跟踪。

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    </system.web>
</configuration>

VS.net 代码:

GetRSS类代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public class GetRss
{
    /// <summary>
    /// 根据文件路径写RSS文件
    /// </summary>
    /// <remarks>
    /// 例如: 
    ///  WriteRss("D:Vs2005GenerateRssRSS_Folder est_tb.xml","test_tb")
    /// 注意:根据表的结构,需要调整生成的RSS源。本实例仅供测试用。
    /// </remarks>
    /// <param name="pathfilename">文件路径</param>
    /// <param name="tablename">表名</param>
    /// <returns>true or false</returns>
    public static bool WriteRss(string pathfilename,string tablename)
    {
        try
        {
            FileInfo finfo = new FileInfo(pathfilename);
            using (FileStream fs = finfo.OpenWrite())
            {
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("UTF-8"));
                sw.WriteLine(GetRss.GetRSSString(tablename));
                sw.Flush();
                sw.Close();
            }
            return true;
        }
        catch (System.Exception ex)
        {
            System.Web.HttpContext.Current.Response.Write(ex.Message);
            return false;
            throw;
        }
    
    }

    /// <summary>
    /// 组织符合最新标准的RSS字符串
    /// 参数:表名。
    /// </summary>
    /// <remarks>
    /// 例如: 
    ///  GetRSS()
    /// 注意:根据表的结构,需要调整生成的RSS源。本实例仅供测试用。
    /// </remarks>
    /// <param name="tablename">表名</param>
    /// <returns>返回一个DataSet 数据源</returns>
    public static string GetRSSString(string Tablename)
    {
        try
        {
            DataSet ds = GetRSSData(Tablename);
            string strRSS = "";
            strRSS = strRSS + "  <?xml version="1.0"?> " + System.Environment.NewLine;
            strRSS = strRSS + "  <rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"" + System.Environment.NewLine;
            strRSS = strRSS + "   xmlns:xsd="http://www.w3.org/2001/XMLSchema"   " + System.Environment.NewLine;
            strRSS = strRSS + "   xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">" + System.Environment.NewLine;
            strRSS = strRSS + "  <channel>" + System.Environment.NewLine;
            strRSS = strRSS + "  <title>订阅标题</title> " + System.Environment.NewLine;
            strRSS = strRSS + "  <link>http://www.**com.cn/</link>" + System.Environment.NewLine;
            strRSS = strRSS + "  <description>描述信息</description>" + System.Environment.NewLine;
            strRSS = strRSS + "  <language>zh-CN</language>" + System.Environment.NewLine;
            strRSS = strRSS + "  <generator>www.**com.cn</generator>  " + System.Environment.NewLine;
            strRSS = strRSS + "  <copyright>北京**公司</copyright> " + System.Environment.NewLine;
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                strRSS = strRSS + " <item>" + System.Environment.NewLine;
                strRSS = strRSS + " <title>" + ds.Tables[0].Rows[i]["Title"] + "</title> " + System.Environment.NewLine;
                strRSS = strRSS + " <link>http://www.**.com.cn/ArticleShow@" + ds.Tables[0].Rows[i]["ID"] + ".html</link> " + System.Environment.NewLine;
                strRSS = strRSS + " <author /> " + System.Environment.NewLine;
                strRSS = strRSS + " <guid>http://www.**.com.cn/ArticleShow@" + ds.Tables[0].Rows[i]["ID"] + ".html</guid>   " + System.Environment.NewLine;
                strRSS = strRSS + " <pubDate>" + Convert.ToDateTime(ds.Tables[0].Rows[i]["AddDate"].ToString()).ToString("yyyy-MM-dd HH:mm") + "</pubDate> " + System.Environment.NewLine;
                strRSS = strRSS + " <comments>http://www.**.com.cn/ArticleShow@" + ds.Tables[0].Rows[i]["ID"] + ".html</comments>   " + System.Environment.NewLine;
                strRSS = strRSS + " <slash:comments>0</slash:comments>    " + System.Environment.NewLine;
                strRSS = strRSS + " <source url="http://www.**.com.cn/ArticleShow@" + ds.Tables[0].Rows[i]["ID"] + ".html">" + ds.Tables[0].Rows[i]["Title"] + " </source>    " + System.Environment.NewLine;
                strRSS = strRSS + " <description>" + ds.Tables[0].Rows[i]["Description"] + "</description>" + System.Environment.NewLine;
                strRSS = strRSS + " </item>" + System.Environment.NewLine;
            }
            strRSS = strRSS + " </channel>" + System.Environment.NewLine;
            strRSS = strRSS + " </rss>" + System.Environment.NewLine;
            return strRSS;
        }
        catch (Exception ex)
        {
            System.Web.HttpContext.Current.Response.Write(ex.Message);
            throw;
        }
    }


    /// <summary>
    /// 获取RSS数据源
    /// 参数:表名。
    /// </summary>
    /// <remarks>
    /// 例如: 
    ///  DataSet ds = GetRSSData(TableName)
    /// 注意:根据表的结构,需要调整生成的RSS源。本实例仅供测试用。
    /// </remarks>
    /// <param name="Tablename">表名</param>
    /// <returns>返回一个DataSet 数据源</returns>
    public static DataSet GetRSSData(string Tablename)
    {
        String DBConnStr = System.Configuration.ConfigurationManager.AppSettings["Db_cfgConn"];
        System.Data.SqlClient.SqlDataAdapter DataAdapter = new System.Data.SqlClient.SqlDataAdapter();
        System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection(DBConnStr);
        if (Connection.State != ConnectionState.Open)
        {
            Connection.Open();
        }

        try
        {
            System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand("SELECT @COLUMNS=@COLUMNS+','+NAME FROM SYS.COLUMNS WHERE OBJECT_ID=OBJECT_ID(@TABLENAME)  ORDER BY  column_id  SET @COLUMNS='SELECT '+STUFF(@COLUMNS,1,1,'')+' FROM '+@TABLENAME+''  EXEC(@COLUMNS) ", Connection);
            Command.CommandType = CommandType.Text;
            Command.Parameters.Add("@TABLENAME", SqlDbType.VarChar, 20);
            Command.Parameters["@TABLENAME"].Value = Tablename;
            Command.Parameters.Add("@COLUMNS", SqlDbType.VarChar, 2000);
            Command.Parameters["@COLUMNS"].Value = "";
            Command.ExecuteNonQuery();
            DataAdapter.SelectCommand = Command;
            DataSet DataSet = new DataSet();
            if (DataSet != null)
            {
                DataAdapter.Fill(DataSet, "table");
            }
            return DataSet;
           
        }
        catch (System.Exception ex)
        {
            System.Web.HttpContext.Current.Response.Write(ex.Message);
            Connection.Close();
            throw;

        }
    }


}


前台代码(注意:html页面无其它html代码)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        string Tablename = "Tb_Test"; //Request.QueryString["TableName"];
        string fname = System.Web.HttpContext.Current.Server.MapPath("RSS_Folder") + "\" + Tablename + ".XML";
        GetRss.WriteRss(fname, Tablename);
    }
}


该代码可以在当前程序下的(RSS_Folder)目录下生成以表命名的Xml文件。

以后可以在其它RSS阅读器中订阅RSS服务了。(包括Foxmail 6.0支持对RSS订阅)

posted @ 2010-11-25 17:01  你妹的sb  阅读(481)  评论(0编辑  收藏  举报
百度一下