0

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.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Paolo B
  • 3,026
  • 5
  • 21
  • 43
  • Notice -- seems like the problem is you are doing .Value on "null" aka null.Value – Tyler Nichols Sep 07 '17 at 19:46
  • What about using the null propagation operator (`?.`), like you did with in your `if` condition... `element.Element("comment")?.Value`. Or just `LineComment = element.Element("comment") == null ? "" : element.Element("comment").Value;` – Rufus L Sep 07 '17 at 19:54

3 Answers3

2

Use Null-conditional (?.) Operator:

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

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

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
2

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
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • 2
    wouldn't `element` be `xe` in your example? Also, you might want to call out that you're using the null conditional operator, and that is where the problem is – Rufus L Sep 07 '17 at 19:57
0

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");
L.B
  • 114,136
  • 19
  • 178
  • 224