I have a customers.xml file that looks like the following:
<?xml version="1.0"?>
<customers>
<customer>
<id>1</id>
<name>Mike</name>
<row test1="attribute1" test2="attribute2"/>
</customer>
<customer>
<id>2</id>
<name>John</name>
</customer>
<customer>
<id>3</id>
<row test1="attribute1"/>
</customer>
</customers>
Some customers have the tag and others do not. When I try to store my xml data in an object I get a NullReferenceException on the tag where it is expecting a value but receives null for those customers that do not have the tag.
CustomerID = (string)e.Element("id"),
CustomerName = (string)e.Element("name"),
Test1Attribute = (string)e.Element("row").Attribute("test1"),
Test2Attribute = (string)e.Element("row").Attribute("test2"),
I thought by not using the .Value property and casting, that LINQ automatically resolves null values pertaining to the tag's attribute like it does for the element property.. What is the best case scenario to handle these null values for tag attributes? and can you explain why no similar errors are thrown for missing elements such as above (ex. customer 3) and likewise for missing attributes (ex. customer 3, test2). Thanks ahead of time!
Here are more details about the exception thrown:
System.NullReferenceException occurred HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Test StackTrace: at Test.Program.<>c.b__2_2(XElement e) in C:\Test\Program.cs:line 89 at System.Linq.Enumerable.WhereSelectEnumerableIterator 2.MoveNext()
at System.Collections.Generic.List 1..ctor(IEnumerable 1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable 1 source) at Test.Program.Main(String[] args) in C:\Test\Program.cs:line 86