【问题标题】:Getting null elements using xelement with c# .net使用带有 c# .net 的 xelement 获取空元素
【发布时间】:2012-11-14 12:44:46
【问题描述】:

让我们考虑以下 xml 文档:

<contact>
    <name>Hines</name>
    <phone>206-555-0144</phone>
    <mobile>425-555-0145</mobile>
</contact>

我从中检索一个值

var value = parent.Element("name").Value;

如果 "name" 不存在,上面的代码将抛出 NullReferenceException,因为 Element 在 C# 中将返回 null 而在 vb.net 中则不会,这将抛出空值。

所以我的问题是确定根节点下方的 xml 节点何时丢失,并改为获取空值。

【问题讨论】:

    标签: c# .net xml linq-to-xml xelement


    【解决方案1】:

    您可以创建一个易于重用的扩展方法。放在静态类中

    public static string ElementValue(this XElement parent, string elementName)
    {
        var xel = parent.Element(elementName);
        return xel == null ? "" : xel.Value;
    }
    

    现在你可以这样称呼它

    string result = parent.ElementValue("name");
    

    更新

    如果您在元素不存在时返回null 而不是空字符串,则可以区分空元素和不存在元素。

    public static string ElementValue(this XElement parent, string elementName)
    {
        var xel = parent.Element(elementName);
        return xel == null ? null : xel.Value;
    }
    

     

    string result = parent.ElementValue("name");
    if (result == null) {
        Console.WriteLine("Element 'name' is missing!");
    } else {
        Console.WriteLine("Name = {0}", result);
    }
    

    编辑

    Microsoft 在 .NET Framework 类库的不同位置使用以下模式

    public static bool TryGetValue(this XElement parent, string elementName,
                                                         out string value)
    {
        var xel = parent.Element(elementName);
        if (xel == null) {
            value = null;
            return false;
        }
        value = xel.Value;
        return true;
    }
    

    可以这样调用

    string result;
    if (parent.TryGetValue("name", out result)) {
        Console.WriteLine("Name = {0}", result);
    }
    

    更新

    在 C# 6.0 (Visual Studio 2015) 中,微软引入了空传播运算符?.,大大简化了事情:

    var value = parent.Element("name")?.Value;
    

    即使未找到该元素,这也会简单地将值设置为 null。

    如果您想返回除null 之外的其他值,也可以将其与合并运算符?? 结合使用:

    var value = parent.Element("name")?.Value ?? "";
    

    【讨论】:

    • 感谢您的代码如果不存在则返回 null,如果存在则返回值,我是对的
    【解决方案2】:

    只需将您的元素转换为一些可以为空的类型。 XElement 有一个bunch of overloaded explicit casting operators,它将元素值转换为所需的类型:

    string value = (string)parent.Element("name");
    

    在这种情况下,如果找不到元素&lt;name&gt;,您将获得值等于null 的字符串。 不会引发 NullReferenceException

    我认为如果 xml 中不存在元素,那么 null 是该元素唯一合适的值。但是如果你真的需要空字符串,那么:

    string value = (string)parent.Element("name") ?? "";
    

    【讨论】:

    • +1。非常优雅的解决方案。这些铸件的唯一问题是智能感知不会显示它们的存在:-(
    • @OlivierJacot-Descombes 谢谢!是的,我花了一些时间来适应元素和属性的转换。不过真的很方便!
    【解决方案3】:
    var value = parent.Element("name") != null ? parent.Element("name").Value : ""
    

    【讨论】:

    • 感谢我如何在布尔值中表示真值或元素存在或假
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多