Confessions of a .NET Developer!

Difference between Elements and Descendants

This is a small post regarding the confusion that most XLINQ developers have when they start learning it, that what is the difference between Elements and Descendants?

Well basically both of them take the same arguments and also both return IEnumerable of type XElement, so what makes them different?
Lets take an Example :
here is the XML(it has a root node “users”) :



So the exercise is the return the collection of node “mname” :
First let us use Elements,

XDocument xDoc=XDocument.Load("C:\MyXml.xml");
 IEnumerable<XElement> query = From XElement elem in xDoc.Element("users").Element("user").Element("model").Elements("mname")
Select elem;

As you can see to get to that node we have to start from the top and reach mname node.
Not to forget that, the above code will return only the first user(ie. Tarun), it won’t go to the next user. I would suggest you not to use Elements.

But that’s not the case with Descendants. With Descendants, it returns all the node mname, irrespective of its parent node.
Like this :

IEnumerable<XElement> query=From XElement elem in xDoc.Descendants("mname")
Select elem;

Hope you got the difference.
Have a nice day!


March 7, 2011 Posted by | LINQ | Leave a comment