Skip to main content

Latest Posts:

Basic Sample: Generate RSS Feed using LINQ To SQL and LINQ To XML
Entry Date: Dec 2007 keywords: XML; LINQ; VS 2008; .net framework 3.5; Visual Studio 2008; LINQ To SQL; LINQ To XML;
Short Description:

Learn LINQ To SQL and LINQ to XML by example

Simple, step by step, sample about how to generate an RSSFeed using LINQ and LINQ TO SQL in only five lines of code.


I wanted to start coding some LINQ stuff... something simple, and maybe a bit stupid, but something real: I decided to create an RSS file generator for my site.

Ok, I know that maybe there are professional tools, or whatever... but I had the opportunity of combining LINQ To SQL (To read from my DB), and LINQ To XML (to generate the XML output), ... realizing that I only need five lines of code to generate my feed using LINQ !!.

Let's start by defining the scenario:

  • --> We have a website that contains a big bunch of articles.
  • --> Each article is stored in a database.
  • --> Every entry in the articles table has the following information:
    Field Name Description
    ID Numeric ID of the article (primary key).
    Title Title of the article.
    RSSDescription Short description about the article's content.
    Content Article content (pure HTML).
    Pub. Date When was the article published.

  • --> The URL to reach a given article is the following: (where XX is the Database ID of the article).

Now let's define our Business need: in order to better promote our site we want to offer RSS Syndication, other sites or portals can read from our RSS XML file a summary of the articles / post available from our blog. The Feed that we are going to generate will have the following structure:

    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <rss version="2.0">
            <title>Name of the site</title>
            <description>Description of the site.</description>

                <title>Title of the post</title>
                <description> short description of the post</description>
            ... Title / link / pubDate / Description ...
            (...) Lot of items... (one per article/post)

What we have to implement: Read from the articles table all the entries (fields: title, pubDate and RSSDescription) , create an RSS XML feed and insert all the rows that we read from the DB in the XML RSS format

Let's start coding:

Create a new Visual Studio Console application project (File >> New Project):

Create new console 


Add a new item to the project, we are going to create a LINQ DBML item (let's name it SampleDB):

Create new LINQ DBML

On the Server Explorer >> add a connection to our SQL Server database. Double click over the new LINQ DBML item created and drop a table from the database connections:

Create new LINQ 


Click on the items and rename the fields to a more friendly ones (we are using an entity, no need to keep horrible database name with prefix), and remove the fields that you are not going to use.

Create new LINQ 


Save and close the DBML.

(*) Note down that the connectionstring is stored in a non secure way in your DBML file, you choose to use integrated security, or not to store user and password, and in your code point to the right connection string using the property of the data context: db.Connection.ConnectionString.

Before start coding let's ensure that we have all the references needed to use LINQ and LINQ XML:

references to LINQ 


and all the "using" in the cs file:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;
    using System.Text;    

Now let's instantiate a DBContext associated to that DBML, and let's read all the entries that we need:

       // Instantiate the SampleDBDataContext (from previously dbml created).
        SampleDBDataContext db = new SampleDBDataContext();

        // Let's assume that our site use            
        string blogURLENG = "{0}";

        // First create all the items node, we will have a substructure like (a collection
        // of items, one per article/post):
        // <item>
        //    <title>Title of the post</title>
        //    <link></link>
        //    <pubDate>2007-11-24T08:12:24.323Z</pubDate>
        //    <description> short description of the post</description>
        // </item>

        var articlesEntries = from p in db.BlogEntries
                                   orderby p.EntryDate
                                   select new XElement("item",
                                                            new XElement("title", p.Title),
                                                            new XElement("link", 

string.Format(blogURLENG, p.ID)),
                                                            new XElement("pubDate", 

                                                            new XElement("description", 


Here I execute a select (using LINQ sintax) retrieve the fields that I need, and encapsulate it in an XElement structure (bunch of XML, with the RSS Item structure). As you can see, I don't want to bother about what type of list is returning me the query, I know that is a list and that it implements the IEnumerable interface, I just declare the variable using "var" and forget about the concrete type.

Let's create the whole XML structure, and inject the articles chunk of XML that we generated in the previous line of code:

      // Now let's fit the items subtree in the whole XML Document:
      // <?xml version="1.0" encoding="utf-8" standalone="yes"?>
      // <rss version="2.0">
      // <channel>
      //    <title>Name of the site</title>
      //    <description>Description of the site.</description>
      //    <link></link>
      //  <item>
      //     ...Article post info, previously created 
      //  </item>
      //  (...) Lot of items... (one per article/post)
      //  </channel>
      // As you can see we can create in the same constructor the declaration, single
      // hardcoded elments (channel), and inside them a list of elements to hang from
      // then channel
      XDocument doc = new XDocument(
          new XDeclaration("1.0", "utf-8", "yes"),                
          new XElement("rss",
              new XAttribute("version", "2.0"),
              new XElement("channel",
                  new XElement("title", "RSS My Sample site"),
                  new XElement("description", "Sample Description for"),
                  new XElement("link", ""),

Quite amazing isn't it? We just define the Document, main elements and start nesting other XElement containing parent nodes, or even list of nodes to insert !!

Next step just save the generated document...

    // Save the resulting XML into a file

As I said in the beginning you get a simple RSS generator just with five lines of code !!!

Page (1) Of 1