Jayant
Jayant

Reputation: 152

getting uppermost descendant in LINQ XML

I understand that in LINQ XElement.Descendants<type>() return all descendant element within a node even if it is inside a descendant node of same type.

XML Eg,

<node1>
  <node5 id="upper">
    <node4>
      <node5 id="lower">
      </node5>
    </node4>
  </node5>

  <node3>
     <node5 id="other">
     </node5>
  </node3>
</node1>

in the above case XElement.Descendants for node5 on node1 returns all descendants "upper", "lower" and "other". The question is that I want the upper most descendants only (node5 with id "upper" and "other" - skip "lower") and skip the one that is inside the upper descendant. I am not able to understand how to do that in a simple one line of code.

Upvotes: 1

Views: 53

Answers (1)

har07
har07

Reputation: 89295

You can try to skip <node5> having ancestor other <node5> so that only outer <node5> selected :

var doc = XElement.Parse("....");
var result = doc.Descendants("node5").Where(o => !o.Ancestors("node5").Any());
foreach (var r in result)
{
    Console.WriteLine(r.ToString());
}

Upvotes: 2

Related Questions