簡體   English   中英

如何獲得給定子節點的所有父母?

[英]How to get all parents for a given child node?

<siteNode controller="a" action="b" title="">
  <siteNode controller="aa" action="bb" title="" />
  <siteNode controller="cc" action="dd" title="">
    <siteNode controller="eee" action="fff" title="" />
    <siteNode controller="eee1" action="fff1" title="" />
  </siteNode>
</siteNode>

如何使用LINQ獲取子節點的父母?

例如,如果我給了controller="eee"元素,我會回來的:

<siteNode controller="a" action="b" title="">
  <siteNode controller="aa" action="bb" title="" />
  <siteNode controller="cc" action="dd" title="">

我需要從上述示例中獲取所有父節點和祖父節點。

你的意思是這樣嗎?

IEnumerable<XElement> GetParents(XElement element)
{
    XElement cParent = element.Parent;
    while (cParent != null)
    {
        yield return cParent;
        cParent = cParent.Parent;
    }
}

編輯:

正如Jeff在評論中指出的那樣,您的示例實際上在您的“父”行之一上有一個結束標記,因此實際上不應包含在內。 如果您的實際意思是與其父元素相比“屬於給定記錄的元素”,則可以使用XNode.NodesBeforeSelf()

暫無
暫無

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

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