199

I have came across both these keywords in the VS IntelliSense. I tried to googling the difference between them and did not get a clear answer. Which one of these have the best performance with small to medium XML files. Thanks

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Luke101
  • 63,072
  • 85
  • 231
  • 359

2 Answers2

321

Elements finds only those elements that are direct descendents, i.e. immediate children.

Descendants finds children at any level, i.e. children, grand-children, etc...


Here is an example demonstrating the difference:

<?xml version="1.0" encoding="utf-8" ?>
<foo>
    <bar>Test 1</bar>
    <baz>
        <bar>Test 2</bar>
    </baz>
    <bar>Test 3</bar>
</foo>

Code:

XDocument doc = XDocument.Load("input.xml");
XElement root = doc.Root;

foreach (XElement e in root.Elements("bar"))
{
    Console.WriteLine("Elements : " + e.Value);
}

foreach (XElement e in root.Descendants("bar"))
{
    Console.WriteLine("Descendants : " + e.Value);
}

Result:

Elements : Test 1
Elements : Test 3
Descendants : Test 1
Descendants : Test 2
Descendants : Test 3

If you know that the elements you want are immediate children then you will get better performance if you use Elements instead of Descendants.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    Great answer, I always thought the two were a little backwards as highlighted in your description (when describing Elements, you always need to use the word "descendant" where as it is a bit more optional when talking about Descendants – Mattisdada Apr 06 '16 at 06:55
24

Descendants will search the entire subtree of the current element for the specified name (or will return a flattened version of the tree if no name is provided), whereas Elements searches only the immediate children of the current element.

Adam Robinson
  • 182,639
  • 35
  • 285
  • 343