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?
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With