hemme
hemme

Reputation: 1652

Parsing an Atom feed via LINQ to XML

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};

Upvotes: 2

Views: 3603

Answers (1)

ChrisF
ChrisF

Reputation: 137148

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.

Upvotes: 3

Related Questions