RSS Feed in ASP.NET

Introduction

This article describes how to create a RSS feed in ASP.Net.

Procedure

To create a RSS feed use the following procedure:

  1. Add the following line in to the RSS page under the page directive line as in the following:

    1. <%@OutputCacheDuration="120"VaryByParam="*"%>  

  2. Create a table with the fields Id, title, description and URL and enter some dummy data like:

    Rss-Feed-in-ASP-net1.jpg

  3. Add the following code on the page load:

     

    1. string connectionString = "Data Source=name;Initial Catalog=db name;Integrated Security=True";  
    2. DataTable d_t = newDataTable();  
    3. SqlConnection conn = newSqlConnection(connectionString);  
    4. using (conn)  
    5. {  
    6.     SqlDataAdapter adp = newSqlDataAdapter("SELECT * from tablename", conn);  
    7.     adp.Fill(d_t);  
    8. }   
    9. Response.Clear();  
    10. Response.ContentType = "text/xml";  
    11. XmlTextWriter Text_Writer = newXmlTextWriter(Response.OutputStream,Encoding.UTF8);  
    12. Text_Writer.WriteStartDocument();  
    13. //Below tags are mandatory rss  
    14. Text_Writer.WriteStartElement("rss");  
    15. Text_Writer.WriteAttributeString("version","2.0");  
    16. // Channel tag will contain RSS feed details  
    17. Text_Writer.WriteStartElement("channel");  
    18. Text_Writer.WriteElementString("title"," ASP.NET ");  
    19. Text_Writer.WriteElementString("link","http://nehaprogrammer.blogspot.com");  
    20. Text_Writer.WriteElementString("description"," C#.NET,ASP.NET ");  
    21. Text_Writer.WriteElementString("copyright","Copyright 2013 - 2014 nehaprogrammer.blogspot.com. All rights reserved.");  
    22. foreach (DataRow oFeedItem in d_t.Rows)  
    23. {  
    24.     Text_Writer.WriteStartElement("item");  
    25.     Text_Writer.WriteElementString("title", oFeedItem["Title"].ToString());  
    26.     Text_Writer.WriteElementString("description", oFeedItem["Description"].ToString());  
    27.     Text_Writer.WriteElementString("link", oFeedItem["URL"].ToString());  
    28.     Text_Writer.WriteEndElement();  
    29. }  
    30. Text_Writer.WriteEndElement();  
    31. Text_Writer.WriteEndElement();  
    32. Text_Writer.WriteEndDocument();  
    33. Text_Writer.Flush();  
    34. Text_Writer.Close();  
    35. Response.End();   

     

Save all and view the page in the browser. It will work perfectly.


Similar Articles