Click here to Skip to main content
15,880,392 members
Articles / Web Development / HTML
Article

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

Rate me:
Please Sign up or sign in to vote.
4.63/5 (5 votes)
23 Oct 2007CPOL3 min read 49.5K   245   61   7
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.

ASP.NET
<%@ 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.

ASP.NET
<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.

C#
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:

C#
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.NET
<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:

ASP.NET
<%@ 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:

C#
/// <summary>
/// Reads XML from a given URL
/// </summary>
/// <param name="sourceFile"></param>
/// <returns></returns>
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)


Written By
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 Pin
savita_Bgm30-Dec-10 17:16
savita_Bgm30-Dec-10 17:16 
GeneralProblem with live server Pin
Abbas_here25-Sep-09 1:18
Abbas_here25-Sep-09 1:18 
GeneralRe: Problem with live server Pin
xbadenx26-Nov-10 4:49
xbadenx26-Nov-10 4:49 
GeneralThnaks it's really helpfull for me Pin
Abbas_here24-Sep-09 22:32
Abbas_here24-Sep-09 22:32 
GeneralNice Article Pin
Hemant.Kamalakar31-Oct-07 20:03
Hemant.Kamalakar31-Oct-07 20:03 
GeneralWhere is the download Pin
Dewey23-Oct-07 12:50
Dewey23-Oct-07 12:50 
GeneralRe: Where is the download Pin
xbadenx23-Oct-07 12:58
xbadenx23-Oct-07 12:58 

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

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