Adding categories to the RSS feed using LINQ to XML by ThinqLinq

Adding categories to the RSS feed using LINQ to XML

Last time, we added categories to the web view of the ThinqLinq site. This time, we're going to add them to the RSS feed. Because RSS is "Really Simple", adding the categories is fairly easy. According to the RSS specification, <category> is an optional sub-element of <item>. It can additionally contain the domain that contains that category. In our case, we will point the domain to our implementation that displays all posts for a given category by passing the category id to the query string of our default page. Thus we would want to insert a category like follows:

<category domain="">LINQ</category>

To refresh your memory, we created last discussed creating RSS in the following post: To add our comments, we need to inject an additional query before inside of each <item> element for the categories. To generate each of the categories for a post, we add a query to project (using the select statement) our new <category> nodes as follows:

     <%= From c In post.CategoryPosts _
              Select <category domain=<%= "Default.aspx?CategoryId" & c.CategoryID %>>
<%= c.Category.Title %></category> %>

Notice here, when we are creating the domain, we can use the CategoryID of the CategoryPosts object from the many-to-many table. To display the actual post's title, we need to drill through the CategoryPost to the child Category object's Title property (c.Category.Title). Putting this all together, Using the magic of LINQ to XML and VB, we arrive at the following statement:

Response.Write(<?xml version="1.0" encoding="UTF-8"?>
<rss version='2.0' xmlns:dc='' xmlns:slash='' xmlns:wfw=''>
<title>Thinq Linq</title>
<description>Thoughts relating to LINQ and Language Integrated Query related topics.</description>
<%= From post In query.ToArray _
            Select <item>
<title><%= post.Title %></title>
                         <link><%= "" & post.Id.ToString %></link>
<pubDate><%= post.PublicationDate.ToString("ddd, dd MMM yyyy hh:mm:ss GMT") %></pubDate>
<guid isPermaLink="false">42f563c8-34ea-4d01-bfe1-2047c2222a74:<%= post.Id %></guid>
<description><%= post.Description %></description>
<%= From c In post.CategoryPosts _
                                  Select <category domain=<%= "Default.aspx?CategoryId" & c.CategoryID %>>
<%= c.Category.Title %></category> %>
</item> %>

If you want to view the resulting feed, browse directly to rather than using the standard RSS feed link which is managed through FeedBurner to allow me to gather additional statistics for this site.

Posted on - Comment
Categories: VB Dev Center - LINQ - VB - Linq to XML -
comments powered by Disqus