c# LINQ to XML Query Expression for elemennt exhist?
-
18-09-2019 - |
Question
<channel>
<title>Best Web Gallery - Flash + CSS Gallery</title>
<link>http://bestwebgallery.com</link>
<description>Featuring the world best web design</description>
<pubDate>09 Dec 2009</pubDate>
<generator>http://wordpress.org/?v=2.3.2</generator>
<language>en</language>
</channel>
<channel>
<title>Best Web Gallery - Flash + CSS Gallery</title>
<link>http://bestwebgallery.com</link>
<description>Featuring the world best web design</description>
// pubDate missing
<generator>http://wordpress.org/?v=2.3.2</generator>
<language>en</language>
</channel>
XDocument rssFeed = XDocument.Load(url);
var feedResources = from details in rssFeed.Descendants("channel")
select new feedResource
{
Title = details.Element("title").Value,
Host = details.Element("link").Value,
Description = details.Element("description").Value,
PublishedOn = DateTime.Parse(details.Element("pubDate").Value),
Generator = details.Element("generator").Value,
Language = details.Element("language").Value
};
How can We check here before trying to get Element "pubDate " or others, because if not checked, throws null reference exception ??
Solution
Don't use Parse
etc; xml typically uses different string representations than it accepts; just cast (note no .Value
):
select new FeedResource
{
Title = (string)details.Element("title"),
Host = (string)details.Element("link"),
Description = (string)details.Element("description"),
PublishedOn = (DateTime?)details.Element("pubDate"),
Generator = (string)details.Element("generator"),
Language = (string)details.Element("language")
}
XElement
has conversion operators to do all the work, returning appropriate values.
OTHER TIPS
My personal preference is to add two extension methods to XElement:
public static string ValueOrDefault(this XElement xml)
{
if (xml == null) return null; // or String.Empty, if you prefer
return xml.Value
}
public static string ValueOrDefault(this XElement xml, string defaultValue)
{
if (xml == null) return defaultValue;
return xml.Value
}
Now your code will look something like:
select new feedResource
{
Title = details.Element("title").ValueOrDefault(),
Host = details.Element("link").ValueOrDefault(),
Description = details.Element("description").ValueOrDefault(),
PublishedOn = DateTime.Parse(details.Element("pubDate").ValueOrDefault(DateTime.Now.ToString())),
Generator = details.Element("generator").ValueOrDefault(),
Language = details.Element("language").ValueOrDefault()
};
Just change the line:
PublishedOn = DateTime.Parse(details.Element("pubDate").Value),
for:
PublishedOn = details.Element("pubDate") != null? DateTime.Parse(details.Element("pubDate").Value) : DateTime.Now,
you can change the DateTime.Now for whatever you want
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow