我使用LINQ和XDocument一起讀取XML文件。這是代碼:使用XDocument&Linq讀取XML - 檢查元素是否爲NULL?
XDocument xml = XDocument.Load(filename);
var q = from b in xml.Descendants("product")
select new
{
name = b.Element("name").Value,
price = b.Element("price").Value,
extra = b.Element("extra1").Value,
deeplink = b.Element("deepLink").Value
};
現在的問題是,在extra1
領域並不總是存在。沒有該節點的XML文件中有項目。如果發生這種情況,它會與NullReferenceException一起崩潰。
有沒有可能包含「檢查是否爲空」,以便我可以防止它崩潰?
+1 - 有趣。 – womp 2010-04-07 17:39:52