XmlDocument Class

System.Xml
Represents an XML document.

The XmlDocument class is the .NET Framework's implementation of the W3C Document Object Model (DOM) Level 3 and provides a convenient way to load, create, and manipulate XML documents in memory.

Summary

Constructors

XmlDocument()

Initializes a new instance of the XmlDocument class.

Returns
A new XmlDocument object.

Properties

XmlElement DocumentElement

Gets the root element of the XML document.

Returns
An XmlElement representing the root element of the XML document. Returns null if there is no root element.
XmlNodeList ChildNodes

Gets a node list representing the children of this node.

Returns
An XmlNodeList representing the children of this node.

Methods

void Load(string url)

Loads the XML document from the specified URL.

Parameters
url: The location of the XML document to load.
Exceptions
ArgumentNullException - url is null.
XmlException - Errors occurred while parsing the XML.
IOException - An I/O error occurred while loading the document.
void LoadXml(string xml)

Loads the XML document from the specified string.

Parameters
xml: The XML string to load.
Exceptions
ArgumentNullException - xml is null.
XmlException - Errors occurred while parsing the XML.
XmlNode CloneNode(bool deep)

Creates a duplicate of this node.

Parameters
deep: true to recursively clone the descendants of the node; false to clone only the node itself.
Returns
The cloned node.

Example

The following example demonstrates how to create an XmlDocument, load XML from a string, and then access its elements.

// Assume this is C# code for demonstration
XmlDocument doc = new XmlDocument();
string xmlString = @"<catalog><book id=""bk101""><author>Gambardella, Matthew</author><title>XML Developer's Guide</title></book></catalog>";

doc.LoadXml(xmlString);

XmlElement root = doc.DocumentElement;
// root is now the <catalog> element

XmlNodeList nodes = doc.SelectNodes("//book");
if (nodes != null) {
    foreach (XmlNode node in nodes) {
        Console.WriteLine(node["title"].InnerText);
    }
}

See Also