Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Linq to XML Descendants and Elements

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

like image 694
Luke101 Avatar asked Sep 13 '10 22:09

Luke101


People also ask

What is descendants in XML?

In the XML family tree , descendant can be identified as the inner element of every outer elements in the hierarchy. For suppose, if we have 2 elements called element A , element B and if the element A is the outer element of element B, then element B will be called as descendant of element A.

What is LINQ to XML?

LINQ to XML is an XML programming interface. LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET programming languages. LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory.


1 Answers

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.

like image 113
Mark Byers Avatar answered Sep 21 '22 01:09

Mark Byers