Displaying RSS Items with C# and ASP.NET

I was looking for a quick and easy way to display RSS feeds on a Web page. I choose to use C# and ASP.NET, thus my options were pretty open. I created a simple function within a script to process the RSS items from a URL for an RSS feed. You should be able to easily use this function or pull the code from it to use as your own.

The function takes a string, rssURL, as its parameter. This string contains contains the RSS URL. The function then sets up a WebRequest item using the rssURL value:

        System.Net.WebRequest myRequest = 
                     System.Net.WebRequest.Create(rssURL);

The response of that request is then placed into a WebResponse object:

        System.Net.WebResponse myResponse = myRequest.GetResponse();

Next the WebResponse object is used to set up a stream to pull out the XML values:

        System.IO.Stream rssStream = 
                     myResponse.GetResponseStream();

This is followed by creating an XmlDocument object that can be used to hold the XML pulled from the stream created from the RSS URL. This XmlDocument object is then loaded with the XML from the stream:

        System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument();
        rssDoc.Load(rssStream);

Now that the XML is loaded into an XmlDocument object within the program, it is easy to pull out the values using XPath. Because this is an RSS feed and not just any XML file, it can be assumed that the RSS standards are being used. In this case, it is assumed that RSS 2.0 is being used. Specific tags can be expected as well as a certain structure for the XML. You can find information on RSS 2.0 at http://blogs.law.harvard.edu/tech/rss.

Specifically, the individual items should be in rss/channel/. Using an XPath express, a list of Item nodes can be created by doing the following:

        System.Xml.XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item"); 

rssItems now contains all of the item nodes from the RSS feed. These can now be processed in order to pull out the specific information wanted. In this case, the title, link, and description of each item are going to be displayed. For each item in rssItems, each the individual tagged element can be grabbed by using the SelectSingleNode method and passing the name of the item. The return value should be assigned to an XMLNode object. The following retrieves a title node:

       System.Xml.XmlNode rssDetail;
       rssDetail = rssItems.Item(i).SelectSingleNode("title");

Now the tags need to be stripped off the element before it will be ready to use. The tags are pulled off by using InnerText. Note that while properly formatted RSS XML should have all these tags, it is best to verify. This can be done by verifying that the value of rssDetail is not null after the SelectSingleNode call is done:

if (rssDetail != null) { title = rssDetail.InnerText; } else { title = ""; }

With that, you have all the code for pulling the items out of a feed. All that is left is to use the method to display the feed. I've included the code for a complete ASP.NET listing that calls two feeds:

Listing SimpleRSSFeed.aspx - complete listing for displaying RSS Feeds

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    public void ProcessRSSItem(string rssURL)
    {
        System.Net.WebRequest myRequest = System.Net.WebRequest.Create(rssURL);
        System.Net.WebResponse myResponse = myRequest.GetResponse();

        System.IO.Stream rssStream = myResponse.GetResponseStream();
        System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument();
        rssDoc.Load(rssStream);

        System.Xml.XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");

        string title = "";
        string link = "";
        string description = "";

        for (int i = 0; i < rssItems.Count; i++)
        {
            System.Xml.XmlNode rssDetail;

            rssDetail = rssItems.Item(i).SelectSingleNode("title");
            if (rssDetail != null)
            {
                title = rssDetail.InnerText;
            }
            else
            {
                title = "";
            }

            rssDetail = rssItems.Item(i).SelectSingleNode("link");
            if (rssDetail != null)
            {
                link = rssDetail.InnerText;
            }
            else
            {
                link = "";
            }

            rssDetail = rssItems.Item(i).SelectSingleNode("description");
            if (rssDetail != null)
            {
                description = rssDetail.InnerText;
            }
            else
            {
                description = "";
            }

            Response.Write("<p><b><a href='" + link + "' target='new'>" + title + "</a></b><br/>");
            Response.Write(description + "</p>");
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <%
                string rssURL = "http://www.codeguru.com/icom_includes/feeds/codeguru/rss-all.xml";
                Response.Write("<font size=5><b>Site: " + rssURL + "</b></font><Br />");
                ProcessRSSItem(rssURL);
                Response.Write("<hr />");

                rssURL = "http://www.developer.com/icom_includes/feeds/special/dev-5.xml";
                Response.Write("<font size=5><b>Site: " + rssURL + "</b></font><Br />");
                ProcessRSSItem(rssURL);
            %>
        </div>
    </form>
</body>
</html>

The output from this listing is shown in the following figure;

# # #



About the Author

Bradley Jones

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page

Downloads

Comments

  • Best!!!

    Posted by Keval Solanki on 03/29/2014 05:09am

    best tutorial i have ever rea for implementing rss! thanks for the code!!

    Reply
  • thank you very much

    Posted by Konstantin on 04/16/2013 10:08am

    thank you very much

    Reply
  • Error running code...

    Posted by SalientKnight on 09/29/2009 11:25am

    When I run this code, I get the error message-- The underlying connection was closed: Unable to connect to the remote server. Most people on the net seem to think that this is caused by a proxy server error, but I have not been able to hack together a solution solves this problem. Would it be possible for you to add a discussion of this, or a follow up article. thanks, -=Sal=-

    Reply
  • Displaying RSS Items with C# and ASP.NET

    Posted by asp.net.csharp.ir on 08/09/2008 01:52am

    thanks , your article is very good. all of best.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds