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!
No comments yet.
- How to convert bytes to BitmapImage WPF
- Auto-fixing height and width of Button in WPF DataGrid
- How to enlarge or re-size Calendar in WPF DatePicker
- Saving forms settings(location, height) using Serialization
- Give underline effect to a textbox in WPF using Adorners
- Tricky delegates
- How to dynamically load assemblies including unreferenced assemblies
- Using Extension methods – Convert Image to Byte or Base64
- Allow numbers or letters and disable right-click in textbox
- How to use Owner Drawn Controls
- WPF Tutorial : Drawing Visual