2012-03-06 75 views
4

我在XDocument上执行以下查询。最后一级.Descendants("Instance")产生形式的XElements的列表:使用LINQ解析XDocument

<Instance>filepath1</Instance> 
<Instance>filepath2</Instance> 
<Instance>filepath3</Instance> 
<Instance>filepath4</Instance> 

查询

List<string> fileNames = xDoc.Descendants("Main") 
         .FirstOrDefault() 
         .Descendants("SecondLevel") 
         .FirstOrDefault() 
         .Descendants("Instance") 
         .Select().ToList(); //this line is not correct. Need to get the instances node values as List<string> 

我怎么能存储值filepath1filepath2 ..在List<string>

+1

像'选择(X => x.Value)'? – 2012-03-06 10:19:44

回答

6

通过使用

.... 
    .Descendants("Instance") 
    .Select(e => e.Value) // project to the string values 
    .ToList(); 
+0

谢谢,它的工作。原谅我的无知,那是什么语法。它看起来像用Lamda表达式编写匿名函数。 – Nemo 2012-03-06 10:23:38

+0

我需要阅读以了解它。 – Nemo 2012-03-06 10:24:21

+1

这是一个lambda表达式。它将找到的XElements转换为它们的字符串值。阅读基本的LINQ,任何教程都可以。 – 2012-03-06 10:28:32