使用LINQ干净地处理嵌套XML的更好方法

Joh*_*ell 5 c# xml linq

我正在使用由嵌套级别获得报酬的人设计的XML.不同的xml文件总是如下所示:

<Car>   
   <Color>
       <Paint>
          <AnotherUselessTag>
               <SomeSemanticBs>
                   <TheImportantData>
Run Code Online (Sandbox Code Playgroud)

使用LINQ很容易得到我想要的东西:(不完全是,但你明白了)

from x in car.Descendants("x")
from y in x.Descendants("y")
from z in y.Descendants("z")
select z.WhatIWant();
Run Code Online (Sandbox Code Playgroud)

我问是否有更好的方法来做到这一点?用Linq导航DOM的一些方法?

Ant*_*nes 8

如果你确定你想要的只是TheImporantData元素中的Car元素而TheImportantData不是用作标记名,那么: -

来自x中的car.Descendants("TheImportantData")选择x.WhatIWant();

会做.


Rob*_*ney 5

考虑XNode扩展方法XPathSelectElements.在你的情况下:

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

Descendants方法不同,以这种方式使用XPath专门导航到您需要的元素 - 例如,它只会查看Color元素下的Car元素,而只会查看Paint元素下的Color元素,依此类推.(如果需要,可以Descendants使用XPath模式模拟方法的区别性较小的行为.//TheImportantData.)