Paolo B
Paolo B

Reputation: 3354

Checking for null values if element does not exist

I am getting values for a number of elements in a .resx file. 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.

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.

Upvotes: 0

Views: 2032

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39956

Use Null-conditional (?.) Operator:

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

It used to test for null before performing a member access.

Upvotes: 2

Erik Philips
Erik Philips

Reputation: 54628

If you're going to use Linq, don't just partially use it: (Just expanding on S. Akbari's Answer)

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

Upvotes: 2

L.B
L.B

Reputation: 116118

Casting an element or attribute to a nullable type is enough. You'll either get the value or null.

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

or

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

Upvotes: 0

Related Questions