I'm currently using Linq to parse an xml file as Linq takes fewer lines of code, but I'm having a small issue with in-consistent xml-files. I'm trying to parse out a Series class from an xml which is basically set up like this:
<series>
<showid>5</showid>
<showname>fringe</showname>
<overview>description of the tv-show fringe.</overview>
</series>
And this is all well and good, this is easily parsed with the following code:
var series = from serie in xdoc.Descendants ("Series")
select new TvShow()
{
ShowID = (string) serie.Element("seriesid").Value,
ShowName = (string) serie.E开发者_开发技巧lement ("SeriesName").Value,
ShowDescription = (string) serie.Element ("Overview").Value,
};
But the problem arrives once i stumble over entries which doesn't have an "overview" tag... Is there a way to return an empty string if the element "overview" doesn't exist?
Absolutely. Don't use the Value
property - use the explicit conversion to string instead. That way you'll get null
if the element doesn't exist, and you can use the null coalescing operator:
var series = from serie in xdoc.Descendants("Series")
select new TvShow()
{
ShowID = (string) serie.Element("seriesid"),
ShowName = (string) serie.Element("SeriesName"),
ShowDescription = (string) serie.Element("Overview") ?? "",
};
(Obviously you can do the same for ShowName and ShowID too.)
Note that all of the custom conversions from XAttribute
and XElement
have a nullable version, e.g. casting to int?
instead of int
... they all work the same way, returning a null value if the original element or attribute is null.
精彩评论