Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to cleanly handle nested XML with LINQ

Tags:

c#

xml

linq

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?

like image 896
John Farrell Avatar asked Jan 08 '09 17:01

John Farrell


2 Answers

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.

like image 116
AnthonyWJones Avatar answered Oct 19 '22 17:10

AnthonyWJones


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.)

like image 41
Robert Rossney Avatar answered Oct 19 '22 18:10

Robert Rossney