linq - XElement NullReferenceException

标签 linq nullreferenceexception xelement

我有以下代码。

 XElement opCoOptOff = doc.Descendants(ns + "OpCoOptOff").FirstOrDefault();
 String opCo = opCoOptOff.Element(ns + "strOpCo").Value;

现在,如果我返回的元素为空,我将收到 NullReferenceException,因为 XElement 为空。所以我将其更改为以下内容。

String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
 if(opCoOptOff != null)
        {
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;

我希望必须有一种更优雅的方法来做到这一点,因为这种情况经常出现,我想避免每次出现问题时都进行这种类型的检查。任何帮助将不胜感激

最佳答案

你可以写一个 extension method并在任何地方使用它:

public static class XDocumentExtension
{
   public static string GetSubElementValue(this XElement element, string item)
   {
        if(element != null && element.Value != null)
        {
           if (element.Element(item) != null)
           {
              return element.Element(item).Value;
           }
        }
        return null;
   }

   public static XElement GetElement(this XElement element, string item)
   {
        if (element != null)
            return element.Element(item);

        return null;
   }

   public static XElement GetElement(this XDocument document, string item)
   {
        if (document != null)
           return document.Descendants("item").FirstOrDefault();
        return null;
   }
}

用作:

String opCo = opCoOptOff.Element(ns + "strOpCo").GetSubElementValue(ns + "strOpCo");

您还可以根据需要添加其他扩展。

编辑:我已经更新了答案,但如果你在我写之前仔细阅读它,你可以为你的目的添加其他扩展。我写这个是因为我猜你可能想调用 null objects Element,我不知道你的具体情况,但我添加了一些代码来进一步说明,根据你的情况完成 XDocumentExtension 类,并且一个注释扩展方法可以在 null 对象上工作。

关于linq - XElement NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4704628/

相关文章:

c# - 方法中的多个 Linq.Tables

c# - 将列表分配给列表框时,未将对象引用设置为对象实例异常

xml - 从 XDocument 中删除 XElement

c# - 延迟加载是否在迭代时加载整个集合?

C# 错误 CS1061 : Type `System.Collections.Generic.List<int>' does not contain a definition for `Length'

.net - LINQ : Generics with IQueryable

c# - ThreadPool.QueueUserWorkItem NullReferenceException

c# - StreamReader NullReferenceException

C# 如何在运行时使用 XElement 使用 Dynamic Linq 创建自定义(动态)类

xml - 当 WCF 方法返回 XmlElement 时,客户端看到 XElement 返回了吗?