I’m working with an xml fragment, and finding that I’m doing the following a lot:
dim x = xe.Element("foo").Element("bar").Element("Hello").Element("World").Value
however I can’t always guarantee that the xml document will contain foo or bar. Is there a nicer way to do this sort of thing without having to null check every query?
i.e.
dim x = ""
if xe.Element("foo").Any() then
if xe.Element("foo").Element("bar").Any() Then
if xe.Element("foo").Element("bar").Element("Hello").Any() Then
x = xe.Element("foo").Element("bar").Element("Hello").Element("World").ValueOrDefault()
End If
End If
End If
(ValueOrDefault is an extension method I’ve added)
Essentially, you’re over analysing the problem.
Start with this:
this will return a sequence of all
<foo>children ofxe; this might be an empty sequence, but will never be null.Now, extend to this:
This uses extension method
Elements()(part of the framework) to look for all<bar>children of the<foo>elements you have so far.Repeat this the whole way down, until you find the element with a value. Then, use a cast to extract the value:
Again, the cast is provided by the framework.
All of the checking for null is already handled for you by the smart coders who wrote the framework – this is a large part of what makes
XDocumentand friends so nice to code with.