使用带有c#.net的xelement获取null元素

时间:2012-11-14 12:44:47

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

让我们考虑以下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节点并改为获取空值。

3 个答案:

答案 0 :(得分:6)

您可以创建一个可以轻松重用的扩展方法。将它放在静态类

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),Microsoft引入了空传播运算符?.,简化了很多事情:

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

即使未找到该元素,也只需将该值设置为null。

如果要返回除??以外的其他值,也可以将其与合并运算符null合并:

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

答案 1 :(得分:4)

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

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

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

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

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

答案 2 :(得分:0)

var value = parent.Element("name") != null ? parent.Element("name").Value : ""