Mantisimo
Mantisimo

Reputation: 4283

LINQ TO XML Parse RSS Feed

I'm trying to parse an RSS feed using LINQ to Xml

This is the rss feed: http://www.surfersvillage.com/rss/rss.xml

My code is as follows to try and parse

List<RSS> results = null;

XNamespace ns = "http://purl.org/rss/1.0/";
XNamespace rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

XDocument xdoc = XDocument.Load("http://www.surfersvillage.com/rss/rss.xml");

results = (from feed in xdoc.Descendants(rdf + "item")
           orderby int.Parse(feed.Element("guid").Value) descending
           let desc = feed.Element("description").Value
           select new RSS
           {
               Title = feed.Element("title").Value,
               Description = desc,
               Link = feed.Element("link").Value
           }).Take(10).ToList();

To test the code I've put a breakpoint in on the first line of the Linq query and tested it in the intermediate window with the following:

xdoc.Element(ns + "channel");

This works and returns an object as expect

i type in:

xdoc.Element(ns + "item");

the above worked and returned a single object but I'm looking for all the items

so i typed in..

xdoc.Elements(ns + "item");

This return nothing even though there are over 10 items, the decendants method doesnt work either and also returned null.

Could anyone give me a few pointers to where I'm going wrong? I've tried substituting the rdf in front as well for the namespace.

Thanks

Upvotes: 0

Views: 2217

Answers (1)

LazyOfT
LazyOfT

Reputation: 1438

You are referencing the wrong namespace. All the elements are using the default namespace rather than the rdf, so you code should be as follow:

List<RSS> results = null;

XNamespace ns = "http://purl.org/rss/1.0/";
XDocument xdoc = XDocument.Load("http://www.surfersvillage.com/rss/rss.xml");
results = (from feed in xdoc.Descendants(ns + "item")
           orderby int.Parse(feed.Element(ns + "guid").Value) descending
           let desc = feed.Element(ns + "description").Value
           select new RSS
           {
               Title = feed.Element(ns + "title").Value,
               Description = desc,
               Link = feed.Element(ns + "link").Value
           }).Take(10).ToList();

Upvotes: 5

Related Questions