使用LINQ解析XDocument

4

我正在对一个XDocument进行以下查询。最后一级.Descendants("Instance")会产生一组形如下面的XElement:

<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
类似于 Select(x=>x.Value) - L.B
1个回答

6
通过使用
 ....
  .Descendants("Instance")
  .Select(e => e.Value) // project to the string values
  .ToList();

谢谢,它起作用了。请原谅我的无知,那是什么语法?它看起来像使用Lambda表达式编写匿名函数。 - Nemo
1
这是一个Lambda表达式。它将找到的XElements转换为它们的字符串值。阅读基本的LINQ知识,任何教程都可以。 - H H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接