簡體   English   中英

如何獲得Linq的后代?

[英]How can I get descendants of descendant in Linq?

編輯:所以我有一個我需要解析的XML文件。 經過研究,我已經能夠獲得沒有問題的第一組節點,而且我非常喜歡可以將其返回的方式。

我已經能夠獲得<Project>的直接子代。 但是獲取下一個后代( <tree><branch )並沒有取得那么多的成就,我終於決定親自問問谷歌和R + D ...如果可能的話,我希望獲得類似的類樣式輸出如下所示,即使代碼已重組。

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

編輯:經過所有的研究,並根據以下答案進行了改進,現在完成的代碼如下,並返回與class相似的var結果。 在進一步研究該項目之后。 我最終得到許多<tree><branch>元素作為父<Project>元素的子節點。 每個樹元素都具有唯一的number屬性。

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() 因為我只想返回一個結果(並且我也不熟悉通過Enumerators進行操作)。 感謝您的答復,並幫助大家!

您需要這樣做:

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元素,如果不是這種情況,則用ToList()替換FirstOrDefault,它將返回所有branch元素。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM