tags:

views:

602

answers:

2

I'm working with XML that was designed by somebody who got paid by the level of nesting. The different xml files always looks something like this:

<Car>   
   <Color>
       <Paint>
          <AnotherUselessTag>
               <SomeSemanticBs>
                   <TheImportantData>

With LINQ its easy to get what I want: ( not exactly, but you get the point )

from x in car.Descendants("x")
from y in x.Descendants("y")
from z in y.Descendants("z")
select z.WhatIWant();

I'm asking if there is a better way to do this? Some way of navigating the DOM with Linq?

+7  A: 

If you are sure that all you want are TheImporantData elements from a Car element and that TheImportantData isn't used as a tag name else where then:-

from x in car.Descendants("TheImportantData") select x.WhatIWant();

Will do.

AnthonyWJones
Thanks, I did not know .Descendants worked like that. Great answer.
jfar
That examines every one of the element's descendant elements, which can be a problem if your XML is very large.
Robert Rossney
@Robert: Interesting point, is there somewhere that can be confirmed. Typical DOMs would index the element names hence selecting by a single name is quite efficient, but Xml.Linq isn't typical.
AnthonyWJones
+4  A: 

Consider the XNode extension method XPathSelectElements. In your case:

var foo = from x in car.XPathSelectElements("Color/Paint/AnotherUselessTag/SomeSemanticBs/TheImportantData")
select x.WhatIWant();

Unlike the Descendants method, using XPath in this fashion navigates specifically to the elements you need - e.g. it will only look at Color elements under the Car element, and only at Paint elements under the Color elements, and so on. (You can emulate the less discriminating behavior of the Descendants method with the XPath pattern .//TheImportantData if you need to.)

Robert Rossney
I wish I could have accepted both answers. This is more what I'm looking for because at least I let the guy behind me know whats going on.
jfar