Best way to clear nested XML with LINQ

I work with XML, which was developed by someone who paid for the level of nesting. Different xml files always look something like this:

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

With LINQ, it's easy to get what I want: (not really, 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 ask, is there a better way to do this? Some way to navigate the DOM with Linq?

+5
source share
2 answers

If you are sure that all you need are TheImporantDataelements from the element Carand that TheImportantDatayou are not using the name of the else tag, where then: -

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

Will do.

+8
source

XNode XPathSelectElements. :

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

Descendants, XPath , - , Color Car Paint Color . ( Descendants XPath .//TheImportantData, .)

+5

All Articles