【发布时间】:2011-02-05 09:06:16
【问题描述】:
我正在使用 LINQ 和 XDocument 来读取 XML 文件。这是代码:
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 而崩溃。
是否有可能包含“检查是否为空”以便防止它崩溃?
【问题讨论】: