我怎样才能在 Linq 中获得后代的后代?

How can I get descendants of descendant in Linq?

编辑: 所以我有一个 XML 文件需要解析。经过研究,我已经能够毫无问题地获得第一组节点,我真的很喜欢我可以 return 它们的方式。

我已经能够得到 <Project> 的立即数 Child。但是得到下一个后代(<tree> & <branch),并没有那么多成果,我最终决定在 google 和 R+D 之后问自己......如果可能的话我'我希望具有如下所示的类似 class 样式的输出,即使代码已重构。

XML结构

<Projects>
 <Project AccessTag="">
  <Title></Title>
  <ReaderURL></ReaderURL>
  <Status></Status>
  <tree>
   <branch></branch>
  </tree>
 </Project>
</Projects>

代码

XDocument xml = XDocument.Load(this.XMLFile);
var project = (
  from p in xml.Descendants("Project")
  where p.Attribute("AccessTag").Value == Trigger
  select new {
    title = p.Element("Title").Value,
    reader = p.Element("ReaderURL").Value,
    status = p.Element("Status").Value
    }).Single();
// output is project.title, project.reader, etc

编辑:经过我所做的所有研究以及基于以下答案的变体,我现在完成的代码如下,并且 returns var 结果类似于 class.在进一步研究该项目之后。我最终得到了许多 <tree><branch> 元素作为 parent <Project> 元素的 child 节点。每个树元素都有一个唯一的数字属性。

XDocument xml = XDocument.Load(this.XMLFile);

var resulted = xml.Descendants("Project")
  .Where(a => (string)a.Attribute("AccessTag") == Trigger)
  .Select(a => new {
    Title = (string)a.Element("Title"),
    ReaderURL = (string)a.Element("ReaderURL"),
    Status = (string)a.Element("Status"),

    Tree = a.Elements("tree")
      .Where(b => (string)b.Attribute("number") == Num)
      .Select(b => new {...}).Single()
  }).FirstOrDefault();

就像下面提到的,在我记得在第二个 .Select() 子句上使用 .Single() 之前,我花了几分钟思考和调试。因为我只想要一个结果 returned(而且我还不熟悉枚举器)。感谢大家的回复,对大家有帮助!

您需要这样做:

from p in xml.Descendants("Project")
from t in p.Descendants("tree") // selecting descendant node tree of Project
  where p.Attribute("AccessTag").Value == Trigger
  select new {
    title = p.Element("Title").Value,
    reader = p.Element("ReaderURL").Value,
    status = p.Element("Status").Value,
    branch = t.Element("branch").Value // select value here
    }).Single();

试试这个:-

var result = xml.Descendants("Project")
           .Where(x => (string)x.Attribute("AccessTag") == "Trigger")
           .Select(x => new
  {
     Title = (string)x.Element("Title"),
     ReaderURL = (string)x.Element("ReaderURL"),
     Status = (string)x.Element("Status"),
     Branch = x.Descendants("tree") //Here are fetching the Descendants
              .Select(z => (string)z.Element("branch")).FirstOrDefault()
   }).FirstOrDefault();

请注意,我在获取 Branch 时使用了 FirstOrDefault,因为我认为您只需要第一个 Branch 元素,如果不是这种情况,请将 FirstOrDefault 替换为 ToList() 和它将 return 所有分支元素。

您可以使用元素而不是后代...

var root = xml.Element("Projects").Element("Project")
              .Where(x => (string)x.Attribute("AccessTag") == "Trigger")
              .Select(x => {...});