【问题标题】:Linq / XML - How do you handle non existing nodes?Linq / XML - 你如何处理不存在的节点?
【发布时间】:2011-03-13 05:14:50
【问题描述】:

我试图弄清楚如何处理我的所有“卡片”元素都不存在的节点。我有以下 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”类型的操作数

我该如何处理这个问题?

谢谢!

【问题讨论】:

    标签: c# xml linq linq-to-xml


    【解决方案1】:

    不要使用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 元素的情况,此不会提供帮助,因为它会尝试取消引用空元素以查找path 属性。如果您需要解决方法,请告诉我,但相对而言,这会有点痛苦。

    编辑:您始终可以自己为此创建扩展方法:

    public static XAttribute NullSafeAttribute(this XElement element, XName name)
    {
        return element == null ? null : element.Attribute(name);
    }
    

    然后这样称呼它:

    Image = (string) deck.Element("Image").NullSafeAttribute("path"),
    

    【讨论】:

    • 解决了!你介意解释一下int是什么吗?做?非常感谢!
    • 就图像而言,它将始终存在。但为什么它不适用于属性?一旦我开始更多地开发我的 XML,我就会发现这是一个问题。
    • @Stacey:一般来说,这对属性来说没问题 - 但你试图找到一个子元素,然后是该元素的 属性。如果 XElement 为 null,则可以调用 XElement 上的扩展方法以返回 XAttribute 或 null。将添加一个示例。
    • 感谢您的帮助。当我开始扩展我的 XML 时,我一定会牢记这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    相关资源
    最近更新 更多