Filtering RSS Feed using LINQ and Binding to an ASP.NET GridView

Posted by: Suprotim Agarwal , on 3/18/2010, in Category LINQ
Views: 76496
Abstract: In this article, we will see how to read and filter the RSS Feed of dotnetcurry.com using LINQ to XML.
Filtering RSS Feed using LINQ and Binding to an ASP.NET GridView
 
In this article, we will see how to read and filter the RSS Feed of dotnetcurry.com using LINQ to XML. We will first read the RSS feed and populate the DropDownList with ‘Authors’ retrieved from the feed. We will then filter the feed results based on the Author selected in the DropDownList.
I assume that you are familiar with ASP.NET and LINQ to XML. If not, I would recommend you to get some hands-on on LINQ to XML. These three articles will help you out:
We will be reading and filtering the RSS feed of this site www.dotnetcurry.com. The RSS feed can be obtained over here http://feeds.feedburner.com/netCurryRecentArticles. Let us quickly jump to the solution.
Step 1: Create a new website (Open Visual Studio > File > New Website) called ‘FilterRSS.
Step 2: Drag and drop a GridView and a DropDownList control to the page.
Step 3: Once you visit the RSS Feed over here, right click on the page and View Source. You will find an XML file, since RSS is an XML file.
A sample portion of the RSS we will be reading, looks similar to the following:
RSS Feed
Let us now write a LINQ to XML query to read the Title, Link, Description and Author elements from our RSS Feed and filter the results. Add the following markup to the DropDownList and some template Columns to the GridView, to display content:
<div>
    <asp:DropDownList ID="DropDownList1" runat="server"
        onselectedindexchanged="DropDownList1_SelectedIndexChanged"
        AutoPostBack="True">
    </asp:DropDownList>
    <br /><br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateField HeaderText="Title">
         <ItemTemplate>
         <a href='<%# Eval("link") %>' target="_blank"><%# Eval("title") %></a>
         </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Author"
           HeaderText="Author" />
       <asp:BoundField DataField="description" HtmlEncode="false"
               HeaderText="Description" />
    </Columns>
    </asp:GridView>
</div>
Step 4: Now create an ArticlesList class which will act as a container for the items read from the feed
C#
 
public class ArticlesList
{
    public string Title { get; set; }
    public string Link { get; set; }
    public string Description { get; set; }
    public string Author { get; set; }
}
 
VB.NET
Public Class ArticlesList
      Private privateTitle As String
      Public Property Title() As String
            Get
                  Return privateTitle
            End Get
            Set(ByVal value As String)
                  privateTitle = value
            End Set
      End Property
      Private privateLink As String
      Public Property Link() As String
            Get
                  Return privateLink
            End Get
            Set(ByVal value As String)
                  privateLink = value
            End Set
      End Property
      Private privateDescription As String
      Public Property Description() As String
            Get
                  Return privateDescription
            End Get
            Set(ByVal value As String)
                  privateDescription = value
            End Set
      End Property
      Private privateAuthor As String
      Public Property Author() As String
            Get
                  Return privateAuthor
            End Get
            Set(ByVal value As String)
                  privateAuthor = value
            End Set
      End Property
End Class
 
We are using Generics to return a strongly typed collection of IEnumerable<ArticlesList> items. This collection can now be passed to any other part of the application or stored in a session object to be used during postbacks.
The code will look similar to the following:
C#
using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            XElement xFeed = XElement.Load(@"http://feeds.feedburner.com/netCurryRecentArticles");
 
            IEnumerable<ArticlesList> items = from item in xFeed.Elements("channel").Elements("item")
                    select new ArticlesList
                    {
                        Title = item.Element("title").Value,
                        Link = item.Element("link").Value,
                        Description = item.Element("description").Value,
                        Author = item.Element("author").Value
                    };
 
            //store items in a session
            Session["feed"] = items;
 
            var authors = items.Select(p => p.Author).Distinct();
 
            DropDownList1.DataSource = authors;
            DropDownList1.DataBind();
            string selAuth = DropDownList1.SelectedValue;
            PopulateGrid(selAuth);
        }
    }
 
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {       
        string selAuth = DropDownList1.SelectedValue;
        PopulateGrid(selAuth);      
    }
 
    protected void PopulateGrid(string author)
    {
        var items = (IEnumerable<ArticlesList>)Session["feed"];
 
        if (items != null)
        {
            var filteredList = from p in items
                               where p.Author == author
                               select p;
 
            GridView1.DataSource = filteredList;
            GridView1.DataBind();
        }
    }
}
 
VB.NET
 
Imports System
Imports System.Linq
Imports System.Xml.Linq
Imports System.Collections.Generic
 
Partial Public Class _Default
      Inherits System.Web.UI.Page
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If (Not IsPostBack) Then
                  Dim xFeed As XElement = XElement.Load("http://feeds.feedburner.com/netCurryRecentArticles")
 
                  Dim items As IEnumerable(Of ArticlesList) = From item In xFeed.Elements("channel").Elements("item") _
                                                              Select New ArticlesList
                                    item.Element("description").Value, Author = item.Element("author").Value
                                    item.Element("link").Value, Description = item.Element("description").Value, Author
                                    item.Element("title").Value, Link = item.Element("link").Value, Description
                                    Title = item.Element("title").Value, Link
 
                  'store items in a session
                  Session("feed") = items
 
                  Dim authors = items.Select(Function(p) p.Author).Distinct()
 
                  DropDownList1.DataSource = authors
                  DropDownList1.DataBind()
                  Dim selAuth As String = DropDownList1.SelectedValue
                  PopulateGrid(selAuth)
            End If
      End Sub
 
      Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            Dim selAuth As String = DropDownList1.SelectedValue
            PopulateGrid(selAuth)
      End Sub
 
      Protected Sub PopulateGrid(ByVal author As String)
            Dim items = CType(Session("feed"), IEnumerable(Of ArticlesList))
 
            If items IsNot Nothing Then
                  Dim filteredList = From p In items _
                                     Where p.Author = author _
                                     Select p
 
                  GridView1.DataSource = filteredList
                  GridView1.DataBind()
            End If
      End Sub
End Class
 
In the code above, we load the Xml from the RSS feed using the XElement class. We then enumerate through all the Channel\Item elements and populate the items collection. This collection is stored in a Session object to be reused during postbacks.
Note: Observe the !IsPostBack which populates the collection only once, thereby saving the list from getting populated on every pageload.
We then apply a filter on this collection and select distinct authors and bind the result to a DropDownList. The selected author is passed to the PopulateGrid() method where the session object is casted back to IEnumerable<T>. The list is then filtered based on the author passed and the results are bound to a GridView.
Similarly as and when the users selects a new author from the DropDownList, the list gets filtered and only the articles belonging to that author is displayed. Here are some screenshots:
DropDownRSS Feed
DropDownRSS Feed
I hope this article was useful and I thank you for viewing it. The entire source code of this article can be downloaded over here
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by kk on Tuesday, February 5, 2013 5:10 AM
kk