使用XDocument和Linq读取XML – 检查元素是否为NULL?

我正在使用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而崩溃。

有没有可能包括“检查是否为空”,以便我可以防止它崩溃?

使用(string)代替.Value

 var q = from b in xml.Descendants("product") select new { name = (string)b.Element("name"), price = (double?)b.Element("price"), extra = (string)b.Element("extra1"), deeplink = (string)b.Element("deepLink") }; 

这也适用于其他数据类型 ,包括许多可空类型,以防元素不总是存在。

您可以使用“null coalescing”运算符:

 var q = from b in xml.Descendants("product") select new { name = (string)b.Element("name") ?? "Default Name", price = (double?)b.Element("price") ?? 0.0, extra = (string)b.Element("extra1") ?? String.Empty, deeplink = (string)b.Element("deepLink") ?? String.Empty }; 

这样,您就可以完全控制没有元素时使用的默认值。

在使用该元素之前,请使用以下示例检查是否存在任何元素。

 if( b.Elements("extra1").Any() ) { extra = b.Element("extra1").Value; } 

以下是使用XDocument读取XML文件的示例示例。

  XDocument objBooksXML = XDocument.Load(Server.MapPath("books.xml")); var objBooks = from book in objBooksXML.Descendants("Book") select new { Title = book.Element("Title").Value, Pages = book.Element("Pages").Value }; Response.Write(String.Format("Total {0} books.", objBooks.Count())); gvBooks.DataSource = objBooks; gvBooks.DataBind();