Click here to Skip to main content
Click here to Skip to main content

RSS/XML Data-Binding to Data Control with Row Limitations

, 23 Oct 2007
Rate this:
Please Sign up or sign in to vote.
This article not only details how to bind an RSS feed (or any XML document) directly to a data control (DataGrid), but also how to limit the number of rows displayed

Introduction

This code will use an RSS feed as a data source for a DataGrid control. Instead of displaying all rows in the feed, row-limiting code is also used.

Background

I built a SEO CMS for the company I work for. One of our clients wanted to include dynamic RSS data on output pages. Since the system can output the entire site to any server environment, this was simple. In this case, the client's ASP.NET environment would be able to handle the dynamic data, as the .NET code could be placed directly in their Web page templates, as the system does not compile any code, only outputs pages.

Binding an RSS feed to a data control is simple, right? What about if you don't want to display all the rows of that feed? Let's say, for a Web site, you have found the perfect feed that will add SEO content to a given page. As not to dilute the content's importance, you only want to display two or three RSS articles from that feed, and not all 15-30.

Using the Code

The following code can be placed entirely on the *.aspx page, but can also be moved to a code-behind page.

We will use System.Data and System.Xml to parse and manipulate the data from a given RSS feed.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>

Next, after indicating the script language, we define the feed and the number of articles to display from the feed.

<script language="C#" runat="server">
    
    const string RSS_FEED = "http://news.google.com/news?hl=en&ned=us&ie=
            UTF-8&q=Living+room+entertainment+furniture&output=rss";
    const int MAX_RSS_ROWS = 2; 

The code to process the RSS feed is contained in GetRSSFeed(). We are not at all concerned about parsing any of the feed, as the XmlTextReader does all of the work for us. After loading the feed, we create a DataSet with the feed data.

Usually, we would just end here, return the DataSet, and bind to our data control. However, what we want to do is limit the amount of data that is actually displayed by the data control.

I did think about using the DataGrid's paging option, and through CSS, setting the paging display index to 'none' - but that's messy.

The next step involves populating a DataView, so we can cycle through the view's rows, and creating a new DataTable, which will contain the limited data set.

protected DataTable GetRSSFeed(string strURL)
{
    XmlTextReader reader = new XmlTextReader(strURL);

    DataSet ds = new DataSet();
    ds.ReadXml(reader);         // populate dataset
        
    // populate dv so we can filter out extra <item> rows
    DataView dv = new DataView(ds.Tables[3]);
    DataTable outputTable = dv.Table.Clone();
        
    // iterate through the dv rows, copy them to the outputTable 
    // until max rows is reached
    for (int x = 0; x < MAX_RSS_ROWS; x++)
    {
        outputTable.ImportRow(dv.Table.Rows[x]);
    }

    return outputTable;
}

The Page_Load() method calls our GetRSSFeed() method, which returns the data source for our DataGrid:

protected void Page_Load(object sender, EventArgs e)
{
    recentPosts.DataSource = GetRSSFeed(RSS_FEED);
    recentPosts.DataBind();
}

Finally, we need to define the DataGrid, and data items to display:

<asp:DataGrid runat="server" id="recentPosts" AutoGenerateColumns="False"
     Font-Name="Arial" Font-Size="10pt"
     HeaderStyle-Font-Bold="True"
     HeaderStyle-HorizontalAlign="Center"
     HeaderStyle-BackColor="Navy" HeaderStyle-ForeColor="White"
     HeaderStyle-Font-Size="15pt"
     AlternatingItemStyle-BackColor="#eeeeee" AllowPaging=false Font-Names="Arial" PageSize="3">
  <Columns>
    <asp:TemplateColumn HeaderStyle-BackColor="Gray" HeaderText="RSS FEED">
      <ItemTemplate>
        <a href="<%# DataBinder.Eval(Container.DataItem, "link")%>">

That's it!

Simply copy/paste the code below into a new *.aspx page. The entire code for the page reads as follows:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>

<script language="C#" runat="server">
    
    const string RSS_FEED = "http://news.google.com/news?hl=en&ned=us&
            ie=UTF-8&q=Living+room+entertainment+furniture&output=rss";
    const int MAX_RSS_ROWS = 2;

    protected void Page_Load(object sender, EventArgs e)
    {
        recentPosts.DataSource = GetRSSFeed(RSS_FEED);
        recentPosts.DataBind();
    }

    protected DataTable GetRSSFeed(string strURL)
    {
        XmlTextReader reader = new XmlTextReader(strURL);

        DataSet ds = new DataSet();
        ds.ReadXml(reader);         // populate dataset
        
        // populate dv so we can filter out extra <item> rows
        DataView dv = new DataView(ds.Tables[3]);
        DataTable outputTable = dv.Table.Clone();
        
        // iterate through the dv rows, copy them to the outputTable 
        // until max rows is reached
        for (int x = 0; x < MAX_RSS_ROWS; x++)
        {
            outputTable.ImportRow(dv.Table.Rows[x]);
        }

        return outputTable;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>RSS</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:DataGrid runat="server" id="recentPosts" AutoGenerateColumns="False"
             Font-Name="Arial" Font-Size="10pt"
             HeaderStyle-Font-Bold="True"
             HeaderStyle-HorizontalAlign="Center"
             HeaderStyle-BackColor="Navy" HeaderStyle-ForeColor="White"
             HeaderStyle-Font-Size="15pt"
             AlternatingItemStyle-BackColor="#eeeeee" 
                AllowPaging=false Font-Names="Arial" PageSize="3">
          <Columns>
            <asp:TemplateColumn HeaderStyle-BackColor="Gray" HeaderText="RSS FEED">
              <ItemTemplate>
                <a href="<%# DataBinder.Eval(Container.DataItem, "link")%>">
                  <%# DataBinder.Eval(Container.DataItem, "title") %></a><br />
                  <%# DataBinder.Eval(Container.DataItem, "description") %>
              </ItemTemplate>
            </asp:TemplateColumn>
          </Columns>
        </asp:DataGrid>        

    </div>
    </form>
</body>
</html>  

I've read several other articles that make this job more complicated than it needs to be, and now, with a few extra lines of code, your reader is customizable.

Points of Interest

One of the things I came across while researching this was a method to simply output the contents of an HTML page/XML page/RSS feed, by simply sending the URL:

/// <span class="code-SummaryComment"><summary></span>
/// Reads XML from a given URL
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="sourceFile"></param></span>
/// <span class="code-SummaryComment"><returns></returns></span>
protected object getXML(string sourceFile)
{
    System.Net.WebRequest myRequest = System.Net.WebRequest.Create(sourceFile);
    System.Net.WebResponse myResponse = myRequest.GetResponse();
    System.Xml.XmlTextReader myReader = 
        new System.Xml.XmlTextReader(myResponse.GetResponseStream());
    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
    doc.Load(myReader);
    return (doc);
} 

History

  • 23rd October, 2007: Initial post

You can copy/paste the entire code listed above, or download the source file from the link at the top of this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

xbadenx
Systems Engineer
United States United States
I am a technical architect/senior software engineer, technical trainer, entrepreneur.
 
I have worked in several sectors from healthcare, to entertainment and global intelligent traffic systems, using .Net, SQL, NoSQL and some of the latest technologies to deliver quality software systems for clients.
 
Past tech flavors include C#, WCF, SOA, MVC, MVVM, Silverlight, Assembler, Pascal, VB, Java/J2EE/EJB/JDBC, Perl, NLTK, TSQL, NoSQL, KendoUI, NodeJS, SignalR, Backbone JS, Angular JS, Latest .Net technologies, Amazon AWS...

Comments and Discussions

 
GeneralCompare Two XML Files Pinmembersavita_Bgm30-Dec-10 17:16 
GeneralProblem with live server PinmemberMember 316998125-Sep-09 1:18 
GeneralRe: Problem with live server Pinmemberxbadenx26-Nov-10 4:49 
GeneralThnaks it's really helpfull for me PinmemberMember 316998124-Sep-09 22:32 
GeneralNice Article PinmemberHemant.Kamalakar31-Oct-07 20:03 
GeneralWhere is the download PinmemberDewey23-Oct-07 12:50 
GeneralRe: Where is the download Pinmemberxbadenx23-Oct-07 12:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 23 Oct 2007
Article Copyright 2007 by xbadenx
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid