XDocument Class Overview
This topic introduces the XDocument class.
The XDocument class contains the information necessary for a valid XML document. This includes an XML declaration, processing instructions, and comments.
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.
An XDocument can contain the following elements:
One XElement object. This is the root node of the XML document.
Any number of XProcessingInstruction objects. A processing instruction communicates information to an application that processes the XML.
Any number of XComment objects. The comments will be siblings to the root element. The XComment object cannot be the first argument in the list, because it is not valid for an XML document to start with a comment.
One XDocumentType for the DTD.
When you serialize an XDocument, even if XDocument.Declaration is null, the output will have an XML declaration if the writer has Writer.Settings.OmitXmlDeclaration set to false (the default).
By default, LINQ to XML sets the version to "1.0", and sets the encoding to "utf-8".
The following code creates an XDocument object and its associated contained objects.
XDocument d = new XDocument( new XComment("This is a comment."), new XProcessingInstruction("xml-stylesheet", "href='mystyle.css' title='Compact' type='text/css'"), new XElement("Pubs", new XElement("Book", new XElement("Title", "Artifacts of Roman Civilization"), new XElement("Author", "Moreno, Jordao") ), new XElement("Book", new XElement("Title", "Midieval Tools and Implements"), new XElement("Author", "Gazit, Inbar") ) ), new XComment("This is another comment.") ); d.Declaration = new XDeclaration("1.0", "utf-8", "true"); Console.WriteLine(d); d.Save("test.xml");
When you examine the file test.xml, you get the following output:
<?xml version="1.0" encoding="utf-8"?> <!--This is a comment.--> <?xml-stylesheet href='mystyle.css' title='Compact' type='text/css'?> <Pubs> <Book> <Title>Artifacts of Roman Civilization</Title> <Author>Moreno, Jordao</Author> </Book> <Book> <Title>Midieval Tools and Implements</Title> <Author>Gazit, Inbar</Author> </Book> </Pubs> <!--This is another comment.-->