I’m using LINQ to XML
I’m having a bear of a time figuring out why I’m getting NullReferenceException on the MyUrl portion of the LINQ selection below. What am I missing?
XElement xmlRssItems = XElement.Parse(e.Result);
podlist.ItemsSource = from rssItem in xmlRssItems.Element("channel").Elements("item")
where rssItem.Element("enclosure") != null
select new PodcastItem
{
Title = (string)rssItem.Element("title"),
MyUrl = new Uri(rssItem.Element("enclosure").Attribute("url").Value)
};
…
public class PodcastItem
{
public string Title { get; set; }
public Uri MyUrl { get; set; }
}
XML:
<rss>
<channel>
<item>
<guid isPermaLink="false">tag:blogger.com,1999:blog-811823720557864449.post-3786706865099847612</guid>
<pubDate>Sun, 20 Feb 2011 02:08:00 +0000</pubDate>
<title>#43 - StarCast: "Mork's Homecoming!"</title>
<link>http://starcastshow.blogspot.com/2011/02/43-starcast-morks-homecoming.html</link>
<author>starcastshow@gmail.com (Garrett Weinzierl & Kyle Fergusson)</author>
<thr:total>1</thr:total>
<enclosure url="http://feedproxy.google.com/~r/starcast_rss/~5/Xf0YXRRMrPU/episode_43.mp3" length="0" type="audio/mpeg" />
<feedburner:origEnclosureLink>http://thestarcast.com/shows/starcast/episode_43.mp3</feedburner:origEnclosureLink>
</item>
THE ISSUE:
*THE PROBLEM WAS THAT IN THE RSS FEED THERE WAS ONE NODE THAT DIDN’T HAVE AN ENCLOSURE ITEM. I ADDED A SIMPLE CHECK FOR NULL AND IT WORKS PERFECTLY. THANKS FOR THE SANITY CHECK.*
Have you edited your rss tag to remove the namespaces? This works fine for me, notice the “xmlns:thr” and “xmlns:feedburner” in the rss element:
Another way to handle it would be to add the namespaces and use XmlReader to load your element: