2

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};
Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
hemme
  • 1,654
  • 1
  • 15
  • 22

1 Answers1

3

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
  • 134,786
  • 31
  • 255
  • 325
  • 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 Jul 07 '10 at 19:36
  • Just for convenience :) http://stackoverflow.com/questions/1290851/linq-with-atom-feeds suggested class is System.ServiceModel.Syndication.SyndicationFeed – rdoubleui Aug 31 '12 at 08:48