XDocument Class

Represents an XML document. The XDocument class is a sealed class derived from the XContainer class. It provides a convenient way to create, load, and save XML documents, including the XML declaration and document type.

Namespace

System.Xml.Linq

Assembly

System.Xml.Linq.dll

Syntax

C#
public sealed class XDocument : XContainer

Remarks

An XDocument object represents a complete XML document, including the XML declaration (<?xml version="1.0" encoding="utf-8"?>) and the document type declaration (<!DOCTYPE ...>). It can contain one or more XDocumentType, XProcessingInstruction, or XComment nodes, and exactly one XElement node as its content.

You can create an XDocument from scratch, or load it from a file, URI, or XmlReader. LINQ to XML provides methods for parsing and manipulating XML documents efficiently.

Constructors

XDocument()

Initializes a new instance of the XDocument class.

C#
public XDocument()

XDocument(Object content)

Initializes a new instance of the XDocument class with the specified content.

C#
public XDocument(object content)

Parameters

Name Description
content An object that contains the content of the document. This can be an XElement, XAttribute, XComment, XProcessingInstruction, or XDocumentType.

Properties

DocumentType

Gets the XDocumentType node of this document.

C#
public XDocumentType DocumentType { get; }

Root

Gets the root element of this document.

C#
public XElement Root { get; }

Methods

Load(String uri)

Loads an XDocument from the specified URI.

C#
public static XDocument Load(string uri)

Parameters

Name Description
uri The URI to load the XML from.

Returns

The loaded XDocument.

Save(String uri)

Saves the XDocument to the specified URI.

C#
public void Save(string uri)

Parameters

Name Description
uri The URI to save the XML to.

Examples

Creating an XDocument
XNamespace ns = "http://www.example.com/";
XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XProcessingInstruction("xml-stylesheet", "href='mystyle.css' title='Compact' type='text/css'"),
    new XComment("This is a comment"),
    new XDocumentType("MySchema", null, "schema.dtd", null),
    new XElement(ns + "Root",
        new XElement("Child1", "Content 1"),
        new XElement("Child2", 123)
    )
);
Console.WriteLine(doc);
                
Loading an XDocument from a string
string xmlString = "<Root><Element>Value</Element></Root>";
XDocument doc = XDocument.Parse(xmlString);
Console.WriteLine(doc.Root.Element("Element").Value); // Output: Value
                
Note: The XDocument class is a fundamental part of LINQ to XML, providing a rich API for XML manipulation in .NET.