Microsoft Docs

XDocument Class

Represents an XML document. Provides methods for loading, saving, and manipulating XML documents.

Syntax

public sealed class XDocument : XContainer

Constructors

Show/Hide

Properties

Show/Hide

Methods

Show/Hide

Example

The following example creates an XML document, adds a declaration and root element, and saves it to a file.

// Create a new XDocument
var doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Books",
        new XElement("Book",
            new XAttribute("ISBN", "978-0131103627"),
            new XElement("Title", "The C Programming Language"),
            new XElement("Author", "Kernighan & Ritchie")
        ),
        new XElement("Book",
            new XAttribute("ISBN", "978-0201616224"),
            new XElement("Title", "The Pragmatic Programmer"),
            new XElement("Author", "Andrew Hunt, David Thomas")
        )
    )
);

// Save to file
doc.Save("books.xml");

// Load and display
var loaded = XDocument.Load("books.xml");
Console.WriteLine(loaded);

See Also