2012-03-06 80 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