Create an RSS Feed In ASP.NET 2.0 C#

Using the XmlTextWrite to output an XML file that serves as an RSS feed.

using System.Data.SqlClient;
using System.Text;
using System.Xml;
...

int copyrightyear = DateTime.Now.Year;
Response.Clear();
Response.ContentType = "text/xml";
XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
writer.WriteStartDocument();
writer.WriteStartElement("rss");
writer.WriteAttributeString("version", "2.0");
writer.WriteStartElement("channel");
writer.WriteElementString("title", "Mikesdotnetting News Feed");
writer.WriteElementString("link", 
  wrap"http://www.mikesdotnetting.com/rss.aspx");
writer.WriteElementString("description", 
  wrap"Latest additions to the rubbish that appears on Mikesdotnetting.com.");
writer.WriteElementString("copyright", "(c) " + copyrightyear.ToString() +
  wrap", Mikesdotnetting. All rights reserved.");
string connectionString = Utils.GetConnString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
  using (SqlCommand objCommand = new SqlCommand("GetRss", conn))
  {
    objCommand.CommandType = CommandType.StoredProcedure;
    conn.Open();
    using (SqlDataReader objReader = objCommand.ExecuteReader())
    {
      while (objReader.Read())
      {
        writer.WriteStartElement("item");
        writer.WriteElementString("title", objReader.GetString(1));
        writer.WriteElementString("description", objReader.GetString(2));
        writer.WriteElementString("link", "http://www.mikesdotnetting.com/Article.aspx?ArticleID=
          wrap" + objReader.GetInt32(0).ToString());
        writer.WriteElementString("pubDate", 
          wrapobjReader.GetDateTime(3).ToString("R"));
        writer.WriteEndElement();
      } 
      objReader.Close();
      conn.Close();
      writer.WriteEndElement();
      writer.WriteEndElement();
      writer.WriteEndDocument();
      writer.Flush();
      writer.Close();
      Response.End();
    }
  }
}

You might also like...