Kirk Evans Blog

.NET From a Markup Perspective

Use LINQ and .NET 3.5 to Convert RSS to JSON

Scott Guthrie posted a great example of how to create a feed reader using LINQ to XML.  Today, I see Tim Heuer’s post on the JavaScriptSerializer type in .NET 3.5.  So, I thought I would mash them up and show how to use LINQ to implement Tim’s idea of converting RSS to JSON.  Unfortunately, the JavaScriptSerializer is marked as obsolete with a note to use the DataContractJsonSerializer instead.  Here is what a generic HTTP Handler would look like that mashes up these techniques using .NET 3.5.

<%@ WebHandler Language=“C#” Class=“Handler” %>

using System;
using System.Web;
using System.Linq;
using System.Xml.Linq;
using System.Web.Script.Serialization;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Collections.Generic;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = “application/json”;

XNamespace slashNamespace = “”;

XDocument rssFeed = XDocument.Load(“”);
var posts = from item in rssFeed.Descendants(“item”)
select new
Title = item.Element(“title”).Value,
Published = DateTime.Parse(item.Element(“pubDate”).Value),
Url = item.Element(“link”).Value,
NumComments = int.Parse(item.Element(slashNamespace + “comments”).Value)

var newPosts = from item in posts
where (DateTime.Now – item.Published).Days < 7
select item;

List<FeedItem> itemsList = new List<FeedItem>();
foreach (var item in newPosts)
itemsList.Add(new FeedItem { Title = item.Title, Published = item.Published, Url = item.Url, NumComments = item.NumComments });

DataContractJsonSerializer ser = new DataContractJsonSerializer(itemsList.GetType());
ser.WriteObject(context.Response.OutputStream, itemsList);


public bool IsReusable {
get {
return false;


public class FeedItem
[DataMember] public string Title { get; set; }
[DataMember] public DateTime Published { get; set; }
[DataMember] public string Url { get; set; }
[DataMember] public int NumComments { get; set; }

Look at how simple that is!  Using LINQ, we are able to get just the posts that were published within the past 7 days, and we serialize the result to JSON.  The results are shown below.

“Title”:“Using WCF, JSON, LINQ, and AJAX: Passing Complex Types to WCF Services with JSON Encoding”,
“Title”:“WCF and LINQ”,
“Title”:“Are you ready for some football?!?!”,

So very cool.  Look at how terse yet readable that code is!  Contrast that to something like this from only a couple of years ago… Getting XML From Somewhere Else, which doesn’t even cover filtering the XML and converting to JSON… which I probably would have transformed using some bizarre XSLT geekery.  This is cleaner and easier to understand.