Linq / XML - 如何处理不存在的节点?
我试图弄清楚如何处理所有“卡片”元素都不存在的节点。我有以下 linq 查询:
FinalDeck = (from deck in xmlDoc.Root.Element("Cards")
.Elements("Card")
select new CardDeck
{
Name = deck.Attribute("name").Value,
Image = deck.Element("Image").Attribute("path").Value,
Usage = (int)deck.Element("Usage"),
Type = deck.Element("Type").Value,
Strength = (int)deck.Element("Ability") ?? 0
}).ToList();
对于“强度”项,我读过另一篇帖子,其中 ??处理空值。但我收到以下错误:
运算符“??”无法应用于“int”和“int”类型的操作数
我该如何处理此问题?
谢谢!
I am trying to figure out how to handle nodes that do not exist for all of my "card" elements. I have the following linq query:
FinalDeck = (from deck in xmlDoc.Root.Element("Cards")
.Elements("Card")
select new CardDeck
{
Name = deck.Attribute("name").Value,
Image = deck.Element("Image").Attribute("path").Value,
Usage = (int)deck.Element("Usage"),
Type = deck.Element("Type").Value,
Strength = (int)deck.Element("Ability") ?? 0
}).ToList();
with the Strength item, I had read another posting that the ?? handles the null. I am getting the following error though:
Operator '??' cannot be applied to operands of type 'int' and 'int'
How do I handle this issue?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要使用
Value
属性,而是转换为string
... 对于int
,转换为int?
反而。如果源XAttribute
/XElement
为 null,则用户定义的到可为 null 类型的转换将返回 null:请注意,这不会对这种情况有帮助其中缺少
Image
元素,然后它将尝试取消引用 null 元素以查找path
属性。如果您需要解决方法,请告诉我,但相对而言,这会有点痛苦。编辑:您始终可以自己为此创建一个扩展方法:
然后像这样调用它:
Rather than use the
Value
property, cast tostring
... and for theint
, cast toint?
instead. The user defined conversions to nullable types will return null if the sourceXAttribute
/XElement
is null:Note that this won't help for the case where the
Image
element is missing, as then it'll try to dereference a null element to find thepath
attribute. Let me know if you want a workaround for that, but it'll be a bit of a pain, relatively speaking.EDIT: You can always create an extension method for this yourself:
Then call it like this: