开发者

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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜