如何检查 LinqToXML 表达式中的 null 属性?
我有一个 LinqToXML 表达式,我试图根据相似的属性选择不同的名称。代码运行良好,我将其放在下面:
var q = xmlDoc.Element("AscentCaptureSetup").Element("FieldTypes")
.Descendants("FieldType")
.Select(c => new { width = c.Attribute("Width").Value,
script = c.Attribute("ScriptName").Value,
sqlType = c.Attribute("SqlType").Value,
enableValues = c.Attribute("EnableValues").Value,
scale = c.Attribute("Scale").Value,
forceMatch = c.Attribute("ForceMatch").Value,
forceMatchCaseSensitive = c.Attribute("ForceMatchCaseSensitive").Value,
sortAlphabetically = c.Attribute("SortAlphabetically").Value,
})
.Distinct();
问题的出现是因为并非所有属性都是必需的,如果省略其中一个属性,例如 sortAlphabetically,我会收到“对象未引用”错误。有道理,但是有没有办法改变查询,仅在属性实际存在时才使用分配新值? (从而绕过任何空指针错误)
I have a LinqToXML expression where I am trying to select distinct names based on similar attributes. The code is working great and I've put it below:
var q = xmlDoc.Element("AscentCaptureSetup").Element("FieldTypes")
.Descendants("FieldType")
.Select(c => new { width = c.Attribute("Width").Value,
script = c.Attribute("ScriptName").Value,
sqlType = c.Attribute("SqlType").Value,
enableValues = c.Attribute("EnableValues").Value,
scale = c.Attribute("Scale").Value,
forceMatch = c.Attribute("ForceMatch").Value,
forceMatchCaseSensitive = c.Attribute("ForceMatchCaseSensitive").Value,
sortAlphabetically = c.Attribute("SortAlphabetically").Value,
})
.Distinct();
The problem arises since not all the attributes are required, and if one of them is omitted, for example sortAlphabetically, I get an Object not Referenced error. Makes sense, but it there a way to alter the query to only use assign the new values if the attribute actually exists? (Thereby bypassing any null pointer errors)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要使用
Value
属性(该属性会在空引用上爆炸),只需将XAttribute
转换为字符串 - 您将得到值,或空引用(如果XAttribute
引用为空)。 (XElement
的工作方式相同,这适用于所有可空类型的转换。)因此您会得到:
其中一些属性听起来应该实际上被转换为
int?
或bool?
,请注意...Instead of using the
Value
property (which will blow up on a null reference), simply cast theXAttribute
to string - you'll either get the value, or a null reference if theXAttribute
reference is null. (XElement
works the same way, and this applies to all conversions to nullable types.)So you'd have:
Some of those attributes sound like they should actually be cast to
int?
orbool?
, mind you...