What is the difference between XElement and XDocument?

advertisements

What is the difference between XElement and XDocument and when do you use each?


XDocument represents a whole XML document. It is normally composed of a number of elements.

XElement represents an XML element (with attributes, children etc). It is part of a larger document.

Use XDocument when working with a whole XML document, XElement when working with an XML element.

For example - XElement has a HasAttributes property indicating whether any attributes exist on the element, but an XDocument doesn't, as such a property is meaningless in the context of a whole XML Document.