2010-12-22 40 views
1

如何修改下面的查詢以正確處理其中一篇文章中缺少「摘要」元素的情況?現在,當發生這種情況時,我得到一個「未設置爲對象實例的對象引用」。Linq2XML missing element

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 
      } 
}; 

回答

1

的問題是,article.Element("Summary")返回null如果元素沒有找到,所以你得到一個NullReferenceException當你試圖讓Value屬性。

要解決這個問題,請注意XElement也有一個explicit conversion to string。這不會拋出如果XElementnull - 你只會得到一個null字符串參考。

所以要解決你的問題,你可以改變這一點:

summary = article.Element("Summary").Value, 

這樣:

summary = (string)article.Element("Summary") 
+0

哇...謝謝。快速準確! – Steve 2010-12-22 21:26:15