我想弄清楚如何处理所有“卡片”元素都不存在的节点。我有以下 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' 类型的操作数
我该如何处理这个问题?
谢谢!
最佳答案
不是使用 Value
属性,而是转换为 string
... 而对于 int
,转换为 int?
代替。如果源 XAttribute
/XElement
为 null,则用户定义的可空类型转换将返回 null:
FinalDeck = (from deck in xmlDoc.Root.Element("Cards")
.Elements("Card")
select new CardDeck
{
Name = (string) deck.Attribute("name"),
Image = (string) deck.Element("Image").Attribute("path"),
Usage = (int?) deck.Element("Usage"),
Type = (string) deck.Element("Type"),
Strength = (int?) deck.Element("Ability") ?? 0
}).ToList();
请注意,对于缺少 Image
元素的情况,这不会有帮助,因为它会尝试取消引用 null 元素以找到 >路径
属性。如果您想要一个解决方法,请告诉我,但相对而言,这会有点麻烦。
编辑:您始终可以自己为此创建一个扩展方法:
public static XAttribute NullSafeAttribute(this XElement element, XName name)
{
return element == null ? null : element.Attribute(name);
}
然后这样调用它:
Image = (string) deck.Element("Image").NullSafeAttribute("path"),
关于c# - Linq/XML - 你如何处理不存在的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5285488/