Problem
Both of these keywords appeared in the VS IntelliSense. I tried googling the difference between them but couldn’t find a definitive answer. Which of these performs best with tiny to medium-sized XML files? Thanks
Asked by Luke101
Solution #1
Only elements with direct descendents, i.e. immediate children, are found by Elements.
Descendants searches for children at all levels, including children, grandchildren, and so on.
Here’s an illustration of 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 the elements you desire are immediate children, using Elements instead of Descendants will give you better results.
Answered by Mark Byers
Solution #2
Elements searches only the immediate children of the current element, whereas Descendants searches the whole subtree of the current element for the specified name (or returns a flattened form of the tree if no name is provided).
Answered by Adam Robinson
Post is based on https://stackoverflow.com/questions/3705020/what-is-the-difference-between-linq-to-xml-descendants-and-elements