Linq2XML missing element
How do I modify the query below to properly handle the case where the "Summary" element is miss开发者_运维知识库ing from one of the articles? Now when that happens I get an "Object reference not set to an instance of an object."
var articles = from article in xmlDoc.Descendants("Article")
select new {
articleId = article.Attribute("ID").Value,
heading = article.Element("Heading").Value,
summary = article.Element("Summary").Value,
contents = article.Element("Contents").Value,
cats = from cat in article.Elements("Categories")
select new {
category = cat.Element("Category").Value
}
};
The problem is that article.Element("Summary")
returns null
if the element is not found, so you get a NullReferenceException
when you try to get the Value property.
To solve this, note that XElement
also has an explicit conversion to string
. This won't throw if the XElement
is null
- you will just get a null
string reference.
So to solve your problem you can change this:
summary = article.Element("Summary").Value,
to this:
summary = (string)article.Element("Summary")
精彩评论