【问题标题】:How to check for null attributes in LinqToXML expressions?如何检查 LinqToXML 表达式中的空属性?
【发布时间】:2011-08-09 00:16:46
【问题描述】:

我有一个 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();

出现问题是因为并非所有属性都是必需的,如果省略其中一个,例如 按字母顺序排序,我会收到 Object not Referenced 错误。有道理,但是如果属性实际存在,是否有办法更改查询以仅使用分配新值? (从而绕过任何空指针错误)

【问题讨论】:

    标签: linq linq-to-xml


    【解决方案1】:

    不要使用Value 属性(这将在空引用上爆炸),只需将XAttribute 转换为字符串 - 您将或者获得值,或者 如果XAttribute 引用为空,则为空引用。 (XElement 的工作方式相同,这适用于所有可空类型的转换。)

    所以你有:

    .Select(c => new { 
         width = (string) c.Attribute("Width"),
         script = (string) c.Attribute("ScriptName"),
         sqlType = (string) c.Attribute("SqlType"),
         enableValues = (string) c.Attribute("EnableValues"),
         scale = (string) c.Attribute("Scale"),
         forceMatch = (string) c.Attribute("ForceMatch"),
         forceMatchCaseSensitive = (string) c.Attribute("ForceMatchCaseSensitive"),
         sortAlphabetically = (string) c.Attribute("SortAlphabetically"),
     })
    

    其中一些属性听起来应该实际上转换为int?bool?,请注意...

    【讨论】:

    • 噢!你喝了咖啡,我没有。演员阵容不错,效果会很好。就目前而言,铸造类型无关紧要,这些变量将仅用于创建日志输出。谢谢乔恩
    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多