Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between XElement and XDocument?

Tags:

c#

.net

xml

vb.net

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

like image 469
Rana Avatar asked Oct 07 '10 08:10

Rana


People also ask

What is an XElement?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.

What is an XDocument?

The XDocument class contains the information necessary for a valid XML document, which includes an XML declaration, processing instructions, and comments. You only have to create XDocument objects if you require the specific functionality provided by the XDocument class.

What is the difference between XDocument and XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.


2 Answers

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.

like image 97
Oded Avatar answered Sep 28 '22 17:09

Oded


From MSDN:

Note that you only have to create XDocument objects if you require the specific functionality provided by the XDocument class. In many circumstances, you can work directly with XElement. Working directly with XElement is a simpler programming model.

XDocument derives from XContainer. Therefore, it can contain child nodes. However, XDocument objects can have only one child XElement node. This reflects the XML standard that there can be only one root element in an XML document.

like image 30
Kent Boogaart Avatar answered Sep 28 '22 17:09

Kent Boogaart