XmlDocument Class

.NET Framework | System.Xml Namespace

Class XmlDocument

Represents an XML document object model (DOM) that can be loaded and manipulated.

Summary

The XmlDocument class provides a way to load, navigate, and modify XML documents in memory. It implements the System.Xml.XmlLoadLoad interface, offering a comprehensive set of methods and properties for working with XML data. This class is fundamental for many XML processing tasks in .NET.

Syntax

public class XmlDocument : XmlNode, IXmlSerializable

Remarks

XmlDocument is part of the .NET Framework's XML Document Object Model (DOM) implementation. It allows you to parse an XML document into a tree structure, enabling you to access and manipulate individual nodes (elements, attributes, text, etc.). Key features include:

Note

For performance-critical scenarios or very large XML documents, consider using System.Xml.XmlReader and System.Xml.XmlWriter for forward-only, read-only access, or the System.Xml.Linq namespace (LINQ to XML) which often provides a more modern and intuitive API.

Constructor Summary

Constructor Description
XmlDocument() Initializes a new instance of the XmlDocument class.
XmlDocument(XmlImplementation impl) Initializes a new instance of the XmlDocument class with the specified XmlImplementation.

Properties

Property Description
DocumentElement Gets the root element of the document (XmlElement).
DocumentType Gets the document type node (XmlDocumentType).
Implementation Gets an XmlImplementation object for the current document.
Name Gets the name of the node. For XmlDocument, this is usually #document.
NodeType Gets the node type. For XmlDocument, this is XmlNodeType.Document.
OwnerDocument Gets the XmlDocument to which this node belongs. For the document node itself, this is null.
Schema Gets or sets the schema against which the XML document is validated.
Supports (inherited) Gets a value indicating whether the DOM implementation supports the specified feature.
Value (inherited) Gets or sets the value of the node. For XmlDocument, this is null.

Methods

Method Description
CreateAttribute(string name) Creates an XmlAttribute.
CreateCDataSection(string data) Creates an XmlCDataSection.
CreateComment(string data) Creates an XmlComment.
CreateDocumentFragment() Creates an XmlDocumentFragment.
CreateElement(string prefix, string localName, string namespaceURI) Creates an XmlElement with the specified prefix, local name, and namespace URI.
CreateElement(string tagName) Creates an XmlElement with the specified tag name.
CreateEntityReference(string name) Creates an XmlEntityReference.
CreateNavigator() Creates an XPathNavigator object for navigating this document.
CreateProcessingInstruction(string target, string data) Creates an XmlProcessingInstruction.
CreateSignificantWhitespace(string whitespace) Creates an XmlSignificantWhitespace node.
CreateTextNode(string text) Creates an XmlText node.
CreateWhitespace(string whitespace) Creates an XmlWhitespace node.
GetElementById(string id) Retrieves an XmlElement with the specified ID attribute value.
GetElementsByTagName(string name) Returns an XmlNodeList containing all the descendant elements with the given tag name.
Load(string filename) Loads the XML document from the specified file.
Load(XmlReader reader) Loads the XML document from the specified XmlReader.
LoadXml(string xml) Loads and parses the specified markup into the XmlDocument.
Save(string filename) Saves the XML document to the specified file.
Save(XmlWriter w) Saves the XML document to the specified XmlWriter.
SelectSingleNode(string xpath) Selects the first XmlNode that matches the XPath query.
SelectNodes(string xpath) Selects a list of all descendant nodes that match the XPath query.
WriteContentTo(XmlWriter w) Saves all the children of the current node to the specified XmlWriter.
WriteTo(XmlWriter w) Saves the current node and all its children to the specified XmlWriter.

Example

using System;
using System.Xml;

public class Example
{
    public static void Main(string[] args)
    {
        // Create an XML document
        XmlDocument doc = new XmlDocument();

        // Load XML from a string
        doc.LoadXml("<catalog><book id='bk101'>" +
                    "<author>Gambardella, Matthew</author>" +
                    "<title>XML Developer's Guide</title>" +
                    "<genre>Computer</genre>" +
                    "<price>44.95</price>" +
                    "<publish_date>2000-10-01</publish_date>" +
                    "<description>An in-depth look at creating applications " +
                    "with XML.</description>" +
                    "</book></catalog>");

        // Get the root element
        XmlElement root = doc.DocumentElement;

        // Select a node using XPath
        XmlNode bookTitle = doc.SelectSingleNode("//book/@title");
        if (bookTitle != null)
        {
            Console.WriteLine("Book Title: " + bookTitle.InnerText);
        }

        // Get elements by tag name
        XmlNodeList bookNodes = doc.GetElementsByTagName("book");
        Console.WriteLine("Number of books: " + bookNodes.Count);

        // Add a new element
        XmlElement newBook = doc.CreateElement("book");
        newBook.SetAttribute("id", "bk102");

        XmlElement author = doc.CreateElement("author");
        author.InnerText = "Ralls, Kim";
        newBook.AppendChild(author);

        XmlElement title = doc.CreateElement("title");
        title.InnerText = "Midnight Rain";
        newBook.AppendChild(title);

        root.AppendChild(newBook);

        // Save the modified document to a string
        Console.WriteLine("\nModified XML:");
        Console.WriteLine(doc.OuterXml);
    }
}