XmlDocument Class
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
-
XmlDocument()
Initializes a new instance of the
XmlDocumentclass. -
XmlElement DocumentElement
Gets the root element of the XML document.
-
XmlNodeList ChildNodes
Gets a node list representing the children of this node.
-
void Load(string url)
Loads the XML document from the specified URL.
-
void LoadXml(string xml)
Loads the XML document from the specified string.
-
XmlNode CloneNode(bool deep)
Creates a duplicate of this node.
Constructors
Initializes a new instance of the XmlDocument class.
- Returns
- A new
XmlDocumentobject.
Properties
Gets the root element of the XML document.
- Returns
- An
XmlElementrepresenting the root element of the XML document. Returnsnullif there is no root element.
Gets a node list representing the children of this node.
- Returns
- An
XmlNodeListrepresenting the children of this node.
Methods
Loads the XML document from the specified URL.
- Parameters
-
url: The location of the XML document to load.
- Exceptions
ArgumentNullException-urlisnull.XmlException- Errors occurred while parsing the XML.IOException- An I/O error occurred while loading the document.
Loads the XML document from the specified string.
- Parameters
-
xml: The XML string to load.
- Exceptions
ArgumentNullException-xmlisnull.XmlException- Errors occurred while parsing the XML.
Creates a duplicate of this node.
- Parameters
-
deep:trueto recursively clone the descendants of the node;falseto 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.
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);
}
}