What is the difference between XElement
and XDocument
and when do you use each?
Here's a practical example from msdn which makes it clear. Assume you have this in test.xml file:
1
2
3
With XDocument if you do this:
foreach (var element in XDocument.Load("test.xml").Elements())
Console.WriteLine(element);
You get this back:
1
2
3
To get the value at Child1
node, you will have to do:
var child1 = XDocument.Load("test.xml").Element("Root").Element("Child1").Value;
Or
var child1 = XDocument.Load("test.xml").Root.Element("Child1").Value;
With XElement if you do this:
foreach (var element in XElement.Load("test.xml").Elements())
Console.WriteLine(element);
You get this back:
1
2
3
To get the value at Child1
node, you will do:
var child1 = XElement.Load("test.xml").Element("Child1").Value;
In short, XElement
ignores the root node while XDocument
doesnt. Roughly, XDocument.Root = XElement
, or XDocument.Root.Elements() = XElement.Elements()
. Both derive from XContainer
. Another minor difference is that XElement
implements IXmlSerializable
which I dont think matters mostly. XElement
would be enough for vast majority of cases where you just want to query the sub nodes. The name confuses me though, so I prefer to use XDocument
.