简体   繁体   English

如果元素不存在,则检查空值

[英]Checking for null values if element does not exist

I am getting values for a number of elements in a .resx file. 我正在获取.resx文件中许多元素的值。 On some of the the data elements the <comment> child element does not exist so when I run the following I will get a NullReferenceException . 在某些data元素上, <comment>子元素不存在,因此当我运行以下命令时,我将获得NullReferenceException

foreach (var node in XDocument.Load(filePath).DescendantNodes())
{
    var element = node as XElement;

    if (element?.Name == "data")
    {
        values.Add(new ResxString
        {
            LineKey = element.Attribute("name").Value,
            LineValue = element.Value.Trim(),
            LineComment = element.Element("comment").Value  //fails here
        });
    }
}

I have tried the following: 我尝试了以下方法:

LineComment = element.Element("comment").Value != null ? 
              element.Element("comment").Value : ""

And: 和:

LineComment = element.Element("comment").Value == null ?
              "" : element.Element("comment").Value

However I am still getting an error? 但是我仍然遇到错误? Any help appreciated. 任何帮助表示赞赏。

Use Null-conditional ( ?. ) Operator: 使用空条件?. )运算符:

LineComment = element.Element("comment")?.Value 

It used to test for null before performing a member access. 它用于执行成员访问之前测试null。

If you're going to use Linq, don't just partially use it: (Just expanding on S. Akbari's Answer ) 如果您要使用Linq,请不要仅仅部分使用它:(只需在S. Akbari的答案上进行扩展)

values = XDocument.Load(filePath)
  .DescendantNodes()
  .Select(dn => dn as XElement)
  .Where(xe => xe?.Name == "data")
  .Select(xe => new new ResxString
  {
         LineKey = element.Attribute("name").Value,
         LineValue = element.Value.Trim(),
         LineComment = element.Element("comment")?.Value 
  })
  .ToList();  // or to array or whatever

Casting an element or attribute to a nullable type is enough. 将元素或属性强制转换为可空类型就足够了。 You'll either get the value or null. 您将获得该值或为null。

var LineComment = (string)element.Element("comment");

or 要么

var LineKey = (string)element.Attribute("name");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM