阅读使用的XDocument&放XML; LINQ - 检查是否元素为空? [英] Reading XML using XDocument & Linq - check if element is NULL?
本文介绍了阅读使用的XDocument&放XML; LINQ - 检查是否元素为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一起使用LINQ用的XDocument读取XML文件。这是code:
I'm using LINQ together with XDocument to read a XML File. This is the code:
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
字段并不总是present。有没有该节点的XML文件中的项目。如果出现这种情况它的崩溃与一个NullReferenceException。
Now the problem is, the extra1
field is not always present. There are items in the XML file without that node. If that happens it's crashing with a NullReferenceException.
有没有可能性,包括检查空这样我就可以从崩溃prevent呢?
Is there any possibility to include a "check if null" so I can prevent it from crashing?
推荐答案
使用(串)
而不是 .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")
};
这也适用于其它数据类型的,包括很多可空类型的情况下,该元素并不总是present。
This also works with other datatypes, including many nullable types in case the element is not always present.
这篇关于阅读使用的XDocument&放XML; LINQ - 检查是否元素为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文