c# - Linq/XML - 你如何处理不存在的节点?

标签 c# xml linq linq-to-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' 类型的操作数

我该如何处理这个问题?

谢谢!

最佳答案

不是使用 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/

相关文章:

c# - 如何避免列表中的重复值统一使用 C#

c# - 如何在 C# 中通过解析 Xml 创建表达式树?

c# - 序列化两个互相引用的对象

c# - 从 PointCollection 中检索成对的点?

c# - 谁拥有 Message Box、View 或 ViewModel?

c# - 如何告诉 Linq to Entities 使用 'Like' 来实现字符串相等?

android - 在 Actionscript 3 Android 中卸载 ByteArray

Android XML 圆角剪裁

c# - .NET 3.5 和 4.5 中 LINQ 查询结果的差异

C# 列表解析 = 纯语法糖?