Recently Scott Guthrie posted a really good article on querying an RSS feed with LINQ to XML. After an initial run through of the article, I felt like something was missing. A good buddy of mine (Dave Yancey), were working on an RSS control and we didn't like having to query the RSS twice. Not to mention we really wanted the Title, description and link of the parent RSS - not just each of the items. our initial query looked something like this:
Dim rssFeed = XDocument.Load(http://weblogs.asp.net/bryansampica/rss.aspx) Dim feedData = From post In rssFeed.Descendants("channel") _ Select post Return feedData
For the project we were working on, it was important that we have the top level channel information, like Title, Description, Link...etc. In the query above, we ended up with an impossible to query result set, a collection of items under the main IEnumerable that couldn't be gotten. I sent an email off to Scott Guthrie about this, whom provided an excellent example by Amanda Silver. (Thanks Amanda and Scott!!)
The key is to requery for the second collection, inside the first query. Much like Nested SQL used to be (which essentially what was happening.)
Dim rssFeed = XDocument.Load("http://blogs.msdn.com/vbteam/rss.xml") Dim entries = From post In rssFeed.<rss>.<channel> _ Select Description = post.<description>.FirstOrDefault.Value, _ Link = post.<link>.Value, _ Channel = post.<title>.Value, _ Items = From item In post.<item> _ Where item.<pubDate>.Value > #11/10/2007# _ Select item.<title>.Value, item.<pubDate>.Value, item.Value For Each post In entries Console.WriteLine("Channel: " & post.Channel) For Each item In post.Items Console.WriteLine("Title: " & item.title) Console.WriteLine("Value: " & item.Value) Next Next Console.ReadLine()
This worked perfectly!
There was also a really really good suggestion about enabling the XML intellisense by including the Schema from XML tool - which is available here.
I gotta tell ya, if you are working with XML - this will make your life ALOT easier.