views:

57

answers:

1

I wrote a code snippet to extract elementary information from an Atom feed (e.g. a SO feed) using a LINQ to XML query.

I'd like to know if there are be cases when this code could fail or if there are more elegant ways.

Thanks for the support.

var url = @"http://stackoverflow.com/feeds";
XDocument rss = XDocument.Load(url);

var q = from i in rss.Root.Elements("{http://www.w3.org/2005/Atom}entry")
select new {
        Title = i.Element("{http://www.w3.org/2005/Atom}title").Value, 
        URL = i.Element("{http://www.w3.org/2005/Atom}link").Attribute("href").Value};
A: 

Well if Element("{http://www.w3.org/2005/Atom}title") or Element("{http://www.w3.org/2005/Atom}link") don't exist then you'll get a null reference exception.

The URL line has two chances to fail as you're looking for the "href" attribute without checking that it actually exists.

You should put some checks in for this and decide what you want to do if either of these elements or the attribute don't exist.

ChrisF
What about the explicit dependance to the Atom 2005 namespace? Is it somewhat avoidable? By the way, I saw that the related question "LINQ with ATOM feeds" quite answers mine :)
Hemme