Let’s say I am expecting XML as follows and I’m trying to pull the data in layer3:
<Layer1>
<Layer2>
<Layer3>Test</Layer3>
</Layer2>
</Layer1>
C#:
var data = doc.Element("Layer1").Element("Layer2").Element("Layer3");
If the layer1 or layer2 elements are missing this will result in a null exception. I’m been wrapping these queries with try/catch and defaulting the variable in the catch block but this method smells. Is there a better way to set the “data” variable to null if any of the layers are missing?
Note the use of Element*s*.
IEnumerable<T : XContainer>.Elementsreturns a collection of the child elements. The collection might be empty, but it won’t be null. Thus, you can chainElementscalls without fear of aNullReferenceException.As a side note, this is what VB does when you write
(although in VB, you’d use the handy
IEnumerable<XElements>.Valueextension method instead of SingleOrDefault, which is, unfortunatley, unavailable in C#. Please leave a comment if you know of a C# equivalent.)