Nice way to do linq to xml multilevel "element" query without having to check for null
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
开发者_JAVA百科
(ValueOrDefault is an extension method I've added)
Essentially, you're over analysing the problem.
Start with this:
xe.Elements("foo")
this will return a sequence of all <foo>
children of xe
; this might be an empty sequence, but will never be null.
Now, extend to this:
xe.Elements("foo")
.Elements("bar")
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:
dim x
= (string) xe.Elements("foo")
.Elements("bar")
.Elements("Hello")
.Elements("World")
.FirstOrDefault()
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 XDocument
and friends so nice to code with.
might require modifying your valueOrDefault extension method a bit. Basic idea:
xe.Elements("foo").Elements("bar").Elements("Hello").Elements("World").FirstOrDefault();
精彩评论