.NET Framework Class Library
XmlDocument Class

Represents an XML document.

You can use this class to load, validate, edit, add, and position XML in a document. For examples, see the Remarks section on this page.

Namespace:   System.Xml
Assembly:  System.Xml (in System.Xml.dll)
Syntax
Public Class XmlDocument _
	Inherits [%$TOPIC/6kza7w4k_en-us_VS_110_3_0_0_0_0%]
public class XmlDocument : [%$TOPIC/6kza7w4k_en-us_VS_110_3_0_1_0_0%]
public ref class XmlDocument : public [%$TOPIC/6kza7w4k_en-us_VS_110_3_0_2_0_0%]
type XmlDocument =  
    class 
        inherit [%$TOPIC/6kza7w4k_en-us_VS_110_3_0_3_0_0%] 
    end
public class XmlDocument extends [%$TOPIC/6kza7w4k_en-us_VS_110_3_0_4_0_0%]

The XmlDocument type exposes the following members.

Constructors
  NameDescription
Public method Supported by the XNA Framework XmlDocumentInitializes a new instance of the XmlDocument class.
Protected method Supported by the XNA Framework XmlDocument(XmlImplementation)Initializes a new instance of the XmlDocument class with the specified XmlImplementation.
Public method Supported by the XNA Framework XmlDocument(XmlNameTable)Initializes a new instance of the XmlDocument class with the specified XmlNameTable.
Top
Properties
  NameDescription
Public property Supported by the XNA Framework AttributesGets an XmlAttributeCollection containing the attributes of this node. (Inherited from XmlNode.)
Public property Supported by the XNA Framework BaseURIGets the base URI of the current node. (Overrides XmlNodeBaseURI.)
Public property Supported by the XNA Framework ChildNodesGets all the child nodes of the node. (Inherited from XmlNode.)
Public property Supported by the XNA Framework DocumentElementGets the root XmlElement for the document.
Public property DocumentTypeGets the node containing the DOCTYPE declaration.
Public property Supported by the XNA Framework FirstChildGets the first child of the node. (Inherited from XmlNode.)
Public property Supported by the XNA Framework HasChildNodesGets a value indicating whether this node has any child nodes. (Inherited from XmlNode.)
Public property Supported by the XNA Framework ImplementationGets the XmlImplementation object for the current document.
Public property Supported by the XNA Framework InnerTextThrows an InvalidOperationException in all cases. (Overrides XmlNodeInnerText.)

In XNA Framework 3.0, this member is inherited from XmlNode InnerText.
Public property Supported by the XNA Framework InnerXmlGets or sets the markup representing the children of the current node. (Overrides XmlNodeInnerXml.)
Public property Supported by the XNA Framework IsReadOnlyGets a value indicating whether the current node is read-only. (Overrides XmlNodeIsReadOnly.)
Public property Supported by the XNA Framework ItemStringGets the first child element with the specified Name. (Inherited from XmlNode.)
Public property Supported by the XNA Framework ItemString, StringGets the first child element with the specified LocalName and NamespaceURI. (Inherited from XmlNode.)
Public property Supported by the XNA Framework LastChildGets the last child of the node. (Inherited from XmlNode.)
Public property Supported by the XNA Framework LocalNameGets the local name of the node. (Overrides XmlNodeLocalName.)
Public property Supported by the XNA Framework NameGets the qualified name of the node. (Overrides XmlNodeName.)
Public property Supported by the XNA Framework NamespaceURIGets the namespace URI of this node. (Inherited from XmlNode.)
Public property Supported by the XNA Framework NameTableGets the XmlNameTable associated with this implementation.
Public property Supported by the XNA Framework NextSiblingGets the node immediately following this node. (Inherited from XmlNode.)
Public property Supported by the XNA Framework NodeTypeGets the type of the current node. (Overrides XmlNodeNodeType.)
Public property Supported by the XNA Framework OuterXmlGets the markup containing this node and all its child nodes. (Inherited from XmlNode.)
Public property Supported by the XNA Framework OwnerDocumentGets the XmlDocument to which the current node belongs. (Overrides XmlNodeOwnerDocument.)
Public property Supported by the XNA Framework ParentNodeGets the parent node of this node (for nodes that can have parents). (Overrides XmlNodeParentNode.)
Public property Supported by the XNA Framework PrefixGets or sets the namespace prefix of this node. (Inherited from XmlNode.)
Public property Supported by the XNA Framework PreserveWhitespaceGets or sets a value indicating whether to preserve white space in element content.
Public property Supported by the XNA Framework PreviousSiblingGets the node immediately preceding this node. (Inherited from XmlNode.)
Public property PreviousTextGets the text node that immediately precedes this node. (Inherited from XmlNode.)
Public property Supported by the XNA Framework SchemaInfoReturns the Post-Schema-Validation-Infoset (PSVI) of the node. (Overrides XmlNodeSchemaInfo.)
Public property Supported by the XNA Framework SchemasGets or sets the XmlSchemaSet object associated with this XmlDocument.
Public property Supported by the XNA Framework ValueGets or sets the value of the node. (Inherited from XmlNode.)
Public property Supported by the XNA Framework XmlResolverSets the XmlResolver to use for resolving external resources.
Top
Methods
  NameDescription
Public method Supported by the XNA Framework AppendChildAdds the specified node to the end of the list of child nodes, of this node. (Inherited from XmlNode.)
Public method Supported by the XNA Framework CloneCreates a duplicate of this node. (Inherited from XmlNode.)
Public method Supported by the XNA Framework CloneNodeCreates a duplicate of this node. (Overrides XmlNodeCloneNode(Boolean).)
Public method Supported by the XNA Framework CreateAttribute(String)Creates an XmlAttribute with the specified Name.
Public method Supported by the XNA Framework CreateAttribute(String, String)Creates an XmlAttribute with the specified qualified name and NamespaceURI.
Public method Supported by the XNA Framework CreateAttribute(String, String, String)Creates an XmlAttribute with the specified Prefix, LocalName, and NamespaceURI.
Public method Supported by the XNA Framework CreateCDataSectionCreates an XmlCDataSection containing the specified data.
Public method Supported by the XNA Framework CreateCommentCreates an XmlComment containing the specified data.
Protected method Supported by the XNA Framework CreateDefaultAttributeCreates a default attribute with the specified prefix, local name and namespace URI.
Public method Supported by the XNA Framework CreateDocumentFragmentCreates an XmlDocumentFragment.
Public method CreateDocumentTypeReturns a new XmlDocumentType object.
Public method Supported by the XNA Framework CreateElement(String)Creates an element with the specified name.
Public method Supported by the XNA Framework CreateElement(String, String)Creates an XmlElement with the qualified name and NamespaceURI.
Public method Supported by the XNA Framework CreateElement(String, String, String)Creates an element with the specified Prefix, LocalName, and NamespaceURI.
Public method Supported by the XNA Framework CreateEntityReferenceCreates an XmlEntityReference with the specified name.
Public method CreateNavigatorCreates a new XPathNavigator object for navigating this document. (Overrides XmlNodeCreateNavigator.)
Protected method CreateNavigator(XmlNode)Creates an XPathNavigator object for navigating this document positioned on the XmlNode specified.
Public method Supported by the XNA Framework CreateNode(String, String, String)Creates an XmlNode with the specified node type, Name, and NamespaceURI.
Public method Supported by the XNA Framework CreateNode(XmlNodeType, String, String)Creates an XmlNode with the specified XmlNodeType, Name, and NamespaceURI.
Public method Supported by the XNA Framework CreateNode(XmlNodeType, String, String, String)Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.
Public method Supported by the XNA Framework CreateProcessingInstructionCreates an XmlProcessingInstruction with the specified name and data.
Public method Supported by the XNA Framework CreateSignificantWhitespaceCreates an XmlSignificantWhitespace node.
Public method Supported by the XNA Framework CreateTextNodeCreates an XmlText with the specified text.
Public method Supported by the XNA Framework CreateWhitespaceCreates an XmlWhitespace node.
Public method Supported by the XNA Framework CreateXmlDeclarationCreates an XmlDeclaration node with the specified values.
Public method Supported by the XNA Framework Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method Supported by the XNA Framework FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetElementByIdGets the XmlElement with the specified ID.
Public method Supported by the XNA Framework GetElementsByTagName(String)Returns an XmlNodeList containing a list of all descendant elements that match the specified Name.
Public method Supported by the XNA Framework GetElementsByTagName(String, String)Returns an XmlNodeList containing a list of all descendant elements that match the specified LocalName and NamespaceURI.
Public method Supported by the XNA Framework GetEnumeratorGet an enumerator that iterates through the child nodes in the current node. (Inherited from XmlNode.)
Public method Supported by the XNA Framework GetHashCodeServes as the default hash function. (Inherited from Object.)
Public method Supported by the XNA Framework GetNamespaceOfPrefixLooks up the closest xmlns declaration for the given prefix that is in scope for the current node and returns the namespace URI in the declaration. (Inherited from XmlNode.)
Public method Supported by the XNA Framework GetPrefixOfNamespaceLooks up the closest xmlns declaration for the given namespace URI that is in scope for the current node and returns the prefix defined in that declaration. (Inherited from XmlNode.)
Public method Supported by the XNA Framework GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method Supported by the XNA Framework ImportNodeImports a node from another document to the current document.
Public method Supported by the XNA Framework InsertAfterInserts the specified node immediately after the specified reference node. (Inherited from XmlNode.)
Public method Supported by the XNA Framework InsertBeforeInserts the specified node immediately before the specified reference node. (Inherited from XmlNode.)
Public method Supported by the XNA Framework Load(Stream)Loads the XML document from the specified stream.
Public method Supported by the XNA Framework Load(String)Loads the XML document from the specified URL.
Public method Supported by the XNA Framework Load(TextReader)Loads the XML document from the specified TextReader.
Public method Supported by the XNA Framework Load(XmlReader)Loads the XML document from the specified XmlReader.
Public method Supported by the XNA Framework LoadXmlLoads the XML document from the specified string.
Protected method Supported by the XNA Framework MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by the XNA Framework NormalizePuts all XmlText nodes in the full depth of the sub-tree underneath this XmlNode into a "normal" form where only markup (that is, tags, comments, processing instructions, CDATA sections, and entity references) separates XmlText nodes, that is, there are no adjacent XmlText nodes. (Inherited from XmlNode.)
Public method Supported by the XNA Framework PrependChildAdds the specified node to the beginning of the list of child nodes for this node. (Inherited from XmlNode.)
Public method Supported by the XNA Framework ReadNodeCreates an XmlNode object based on the information in the XmlReader. The reader must be positioned on a node or attribute.
Public method Supported by the XNA Framework RemoveAllRemoves all the child nodes and/or attributes of the current node. (Inherited from XmlNode.)
Public method Supported by the XNA Framework RemoveChildRemoves specified child node. (Inherited from XmlNode.)
Public method Supported by the XNA Framework ReplaceChildReplaces the child node oldChild with newChild node. (Inherited from XmlNode.)
Public method Supported by the XNA Framework Save(Stream)Saves the XML document to the specified stream.
Public method Supported by the XNA Framework Save(String)Saves the XML document to the specified file. If the specified file exists, this method overwrites it.
Public method Supported by the XNA Framework Save(TextWriter)Saves the XML document to the specified TextWriter.
Public method Supported by the XNA Framework Save(XmlWriter)Saves the XML document to the specified XmlWriter.
Public method Supported by the XNA Framework SelectNodes(String)Selects a list of nodes matching the XPath expression. (Inherited from XmlNode.)
Public method Supported by the XNA Framework SelectNodes(String, XmlNamespaceManager)Selects a list of nodes matching the XPath expression. Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager. (Inherited from XmlNode.)
Public method Supported by the XNA Framework SelectSingleNode(String)Selects the first XmlNode that matches the XPath expression. (Inherited from XmlNode.)
Public method Supported by the XNA Framework SelectSingleNode(String, XmlNamespaceManager)Selects the first XmlNode that matches the XPath expression. Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager. (Inherited from XmlNode.)
Public method Supported by the XNA Framework SupportsTests if the DOM implementation implements a specific feature. (Inherited from XmlNode.)
Public method Supported by the XNA Framework ToStringReturns a string that represents the current object. (Inherited from Object.)
Public method Supported by the XNA Framework Validate(ValidationEventHandler)Validates the XmlDocument against the XML Schema Definition Language (XSD) schemas contained in the Schemas property.
Public method Supported by the XNA Framework Validate(ValidationEventHandler, XmlNode)Validates the XmlNode object specified against the XML Schema Definition Language (XSD) schemas in the Schemas property.
Public method Supported by the XNA Framework WriteContentToSaves all the children of the XmlDocument node to the specified XmlWriter. (Overrides XmlNodeWriteContentTo(XmlWriter).)
Public method Supported by the XNA Framework WriteToSaves the XmlDocument node to the specified XmlWriter. (Overrides XmlNodeWriteTo(XmlWriter).)
Top
Events
  NameDescription
Public event Supported by the XNA Framework NodeChangedOccurs when the Value of a node belonging to this document has been changed.
Public event Supported by the XNA Framework NodeChangingOccurs when the Value of a node belonging to this document is about to be changed.
Public event Supported by the XNA Framework NodeInsertedOccurs when a node belonging to this document has been inserted into another node.
Public event Supported by the XNA Framework NodeInsertingOccurs when a node belonging to this document is about to be inserted into another node.
Public event Supported by the XNA Framework NodeRemovedOccurs when a node belonging to this document has been removed from its parent.
Public event Supported by the XNA Framework NodeRemovingOccurs when a node belonging to this document is about to be removed from the document.
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implemetation Private method Supported by the XNA Framework ICloneableCloneFor a description of this member, see XmlNodeClone. (Inherited from XmlNode.)
Explicit interface implemetation Private method Supported by the XNA Framework IEnumerableGetEnumeratorFor a description of this member, see XmlNodeGetEnumerator. (Inherited from XmlNode.)
Top
Remarks

The XmlDocument class is an in-memory representation of an XML document. It implements the W3C Document Object Model (DOM) Level 1 Core and the Core DOM Level 2.

DOM stands for document object model. To read more about it, see XML Document Object Model (DOM).

You can load XML into the DOM by using the XmlDocument class, and then programatically read, modify, and remove XML in the document.

If you want to pry open the XmlDocument class and see how it’s implemented, see the Reference Source.

Tasks

  • Load XML into the DOM

  • Validate it against a schema

  • Navigate the document tree

  • Find nodes

  • Edit nodes

  • Add nodes

  • Remove nodes

  • Position nodes

Load XML into the document object model

Start with an XML document like this one. It’s just a few books in a collection. But it does contain the basic things that you’d find in any XML document; a namespace, elements that represent data and attributes that describe the data.

<?xml version="1.0" encoding="utf-8"?>
<books xmlns="http://www.contoso.com/books">
  <book genre="novel" ISBN="1-861001-57-8" publicationdate="1823-01-28">
    <title>Pride And Prejudice</title>
    <price>24.95</price>
  </book>
  <book genre="novel" ISBN="1-861002-30-1" publicationdate="1985-01-01">
    <title>The Handmaid's Tale</title>
    <price>29.95</price>
  </book>
  <book genre="novel" ISBN="1-861001-45-3" publicationdate="1811-01-01">
    <title>Sense and Sensibility</title>
    <price>19.95</price>
  </book>
</books>

Next, load this data into the DOM so that you can work with it in memory. The most popular way to do this is refer to a file on your local computer or on a network.

This example loads XML from a file. If the file doesn’t exist, it just generates some XML and loads that.

Dim doc As XmlDocument = New XmlDocument
doc.PreserveWhitespace = True 
Try
    doc.Load("booksData.xml")
Catch ex As System.IO.FileNotFoundException
    ' If no file is found, generate some XML.
    doc.LoadXml("<?xml version=""1.0""?> " & ControlChars.NewLine & _
        "<books xmlns=""http://www.contoso.com/books""> " & ControlChars.NewLine & _
        "  <book genre=""novel"" ISBN=""1-861001-57-8"" publicationdate=""1823-01-28""> " & ControlChars.NewLine & _
        "    <title>Pride And Prejudice</title> " & ControlChars.NewLine & _
        "    <price>24.95</price> " & ControlChars.NewLine & _
        "  </book> " & ControlChars.NewLine & _
        "  <book genre=""novel"" ISBN=""1-861002-30-1"" publicationdate=""1985-01-01""> " & ControlChars.NewLine & _
        "    <title>The Handmaid's Tale</title> " & ControlChars.NewLine & _
        "    <price>29.95</price> " & ControlChars.NewLine & _
        "  </book> " & ControlChars.NewLine & _
        "</books>")
End Try
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
try { doc.Load("booksData.xml"); }
catch (System.IO.FileNotFoundException)
{
    doc.LoadXml("<?xml version=\"1.0\"?> \n" +
    "<books xmlns=\"http://www.contoso.com/books\"> \n" +
    "  <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
    "    <title>Pride And Prejudice</title> \n" +
    "    <price>24.95</price> \n" +
    "  </book> \n" +
    "  <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
    "    <title>The Handmaid's Tale</title> \n" +
    "    <price>29.95</price> \n" +
    "  </book> \n" +
    "</books>");             
}
	XmlDocument ^doc = gcnew XmlDocument();
	doc->PreserveWhitespace = true;
	try
	{doc->Load("booksData.xml");}
	catch (System::IO::FileNotFoundException ^e1)
	{
		// If no book is found, generate some XML.

		doc->LoadXml("<?xml version=\"1.0\"?> \n" +
		"<books xmlns=\"http://www.contoso.com/books\"> \n" +
		"  <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
		"    <title>Pride And Prejudice</title> \n" +
		"    <price>24.95</price> \n" +
		"  </book> \n" +
		"  <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
		"    <title>The Handmaid's Tale</title> \n" +
		"    <price>29.95</price> \n" +
		"  </book> \n" +
		"</books>");
	}

Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Learn more: Reading an XML Document into the DOM

Validate it against a schema

Start with an XML schema like this one. This schema defines the data types in the XML and which attributes are required.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  attributeFormDefault="unqualified" 
  elementFormDefault="qualified"
  targetNamespace="http://www.contoso.com/books"> 
  <xs:element name="books">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="book">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="title" type="xs:string" />
              <xs:element name="price" type="xs:decimal" />
            </xs:sequence>
            <xs:attribute name="genre" type="xs:string" use="required" />
            <xs:attribute name="ISBN" type="xs:string" use="required" />
            <xs:attribute name="publicationdate" type="xs:date" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Create an XmlReader object by using your schema, and then load that object into the DOM. Create an event handler that executes when code attempts to modify your XML file in ways that violate the rules of the schema.

These blocks of code show helper methods that do all of this.

'************************************************************************************ 
' 
'  Associate the schema with XML. Then, load the XML and validate it against 
'  the schema. 
' 
'************************************************************************************ 
Public Function LoadDocumentWithSchemaValidation(ByVal generateXML As Boolean, ByVal generateSchema As Boolean) As XmlDocument
    Dim reader As XmlReader
    Dim settings As XmlReaderSettings = New XmlReaderSettings
    ' Helper method to retrieve schema. 
    Dim schema As XmlSchema = getSchema(generateSchema)
    If (schema Is Nothing) Then 
        Return Nothing 
    End If
    settings.Schemas.Add(schema)
    AddHandler settings.ValidationEventHandler, AddressOf settings_ValidationEventHandler
    settings.ValidationFlags = (settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings)
    settings.ValidationType = ValidationType.Schema
    Try
        reader = XmlReader.Create("booksData.xml", settings)
    Catch ex As System.IO.FileNotFoundException
        If generateXML Then 
            Dim xml As String = generateXMLString()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xml)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            reader = XmlReader.Create(stream, settings)
        Else 
            Return Nothing 
        End If 
    End Try 
    Dim doc As XmlDocument = New XmlDocument
    doc.PreserveWhitespace = True
    doc.Load(reader)
    reader.Close()
    Return doc
End Function 

'************************************************************************************ 
' 
'  Helper method that generates an XML Schema. 
' 
'************************************************************************************ 
Private Function generateXMLSchema() As String 

    Dim generatedXmlSchema As String = "<?xml version=""1.0"" encoding=""utf-8""?> " & _
            "<xs:schema attributeFormDefault=""unqualified"" " & _
            "elementFormDefault=""qualified"" targetNamespace=""http://www.contoso.com/books"" " & _
            "xmlns:xs=""http://www.w3.org/2001/XMLSchema""> " & _
            "<xs:element name=""books""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element maxOccurs=""unbounded"" name=""book""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element name=""title"" type=""xs:string"" /> " & _
            "<xs:element name=""price"" type=""xs:decimal"" /> " & _
            "</xs:sequence> " & _
            "<xs:attribute name=""genre"" type=""xs:string"" use=""required"" /> " & _
            "<xs:attribute name=""publicationdate"" type=""xs:date"" use=""required"" /> " & _
            "<xs:attribute name=""ISBN"" type=""xs:string"" use=""required"" /> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:sequence> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:schema> " 


    Return generatedXmlSchema

End Function 

'************************************************************************************ 
' 
'  Helper method that gets a schema 
' 
'************************************************************************************ 
Private Function getSchema(ByVal generateSchema As Boolean) As XmlSchema
    Dim xs As XmlSchemaSet = New XmlSchemaSet
    Dim schema As XmlSchema
    Try
        schema = xs.Add("http://www.contoso.com/books", "booksData.xsd")
    Catch ex As System.IO.FileNotFoundException
        If generateSchema Then 
            Dim xmlSchemaString As String = generateXMLSchema()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xmlSchemaString)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            Dim reader As XmlReader = XmlReader.Create(stream)
            schema = xs.Add("http://www.contoso.com/books", reader)
        Else 
            Return Nothing 
        End If 
    End Try 
    Return schema
End Function 

'************************************************************************************ 
' 
'  Helper method to validate the XML against the schema. 
' 
'************************************************************************************ 
Private Sub validateXML(ByVal generateSchema As Boolean, ByVal doc As XmlDocument)
    If (doc.Schemas.Count = 0) Then 
        ' Helper method to retrieve schema. 
        Dim schema As XmlSchema = getSchema(generateSchema)
        doc.Schemas.Add(schema)
    End If 
    ' Use an event handler to validate the XML node against the schema.
    doc.Validate(AddressOf settings_ValidationEventHandler)
End Sub 

'************************************************************************************ 
' 
'  Event handler that is raised when XML doesn't validate against the schema. 
' 
'************************************************************************************ 
Private Sub settings_ValidationEventHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs)
    If (e.Severity = XmlSeverityType.Warning) Then
        System.Windows.Forms.MessageBox.Show(("The following validation warning occurred: " & e.Message))
    ElseIf (e.Severity = XmlSeverityType.Error) Then
        System.Windows.Forms.MessageBox.Show(("The following critical validation errors occurred: " & e.Message))
        Dim objectType As Type = sender.GetType 
    End If 
End Sub
//************************************************************************************ 
// 
//  Associate the schema with XML. Then, load the XML and validate it against 
//  the schema. 
// 
//************************************************************************************ 
public XmlDocument LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
    XmlReader reader;

    XmlReaderSettings settings = new XmlReaderSettings();

    // Helper method to retrieve schema.
    XmlSchema schema = getSchema(generateSchema);

    if (schema == null)
    {
        return null;
    }

    settings.Schemas.Add(schema);

    settings.ValidationEventHandler += settings_ValidationEventHandler;
    settings.ValidationFlags =
        settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
    settings.ValidationType = ValidationType.Schema;

    try
    {
        reader = XmlReader.Create("booksData.xml", settings);
    }
    catch (System.IO.FileNotFoundException)
    {
        if (generateXML)
        {
            string xml = generateXMLString();
            byte[] byteArray = Encoding.UTF8.GetBytes(xml);
            MemoryStream stream = new MemoryStream(byteArray);
            reader = XmlReader.Create(stream, settings);
        }
        else
        {
            return null;
        }

    }

    XmlDocument doc = new XmlDocument();
    doc.PreserveWhitespace = true;
    doc.Load(reader);
    reader.Close();

    return doc;
}

//************************************************************************************ 
// 
//  Helper method that generates an XML Schema. 
// 
//************************************************************************************ 
private string generateXMLSchema()
{
    string xmlSchema =
        "<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
        "<xs:schema attributeFormDefault=\"unqualified\" " +
        "elementFormDefault=\"qualified\" targetNamespace=\"http://www.contoso.com/books\" " +
        "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"> " +
        "<xs:element name=\"books\"> " +
        "<xs:complexType> " +
        "<xs:sequence> " +
        "<xs:element maxOccurs=\"unbounded\" name=\"book\"> " +
        "<xs:complexType> " +
        "<xs:sequence> " +
        "<xs:element name=\"title\" type=\"xs:string\" /> " +
        "<xs:element name=\"price\" type=\"xs:decimal\" /> " +
        "</xs:sequence> " +
        "<xs:attribute name=\"genre\" type=\"xs:string\" use=\"required\" /> " +
        "<xs:attribute name=\"publicationdate\" type=\"xs:date\" use=\"required\" /> " +
        "<xs:attribute name=\"ISBN\" type=\"xs:string\" use=\"required\" /> " +
        "</xs:complexType> " +
        "</xs:element> " +
        "</xs:sequence> " +
        "</xs:complexType> " +
        "</xs:element> " +
        "</xs:schema> ";
    return xmlSchema;
}

//************************************************************************************ 
// 
//  Helper method that gets a schema 
// 
//************************************************************************************ 
private XmlSchema getSchema(bool generateSchema)
{
    XmlSchemaSet xs = new XmlSchemaSet();
    XmlSchema schema;
    try
    {
        schema = xs.Add("http://www.contoso.com/books", "booksData.xsd");
    }
    catch (System.IO.FileNotFoundException)
    {
        if (generateSchema)
        {
            string xmlSchemaString = generateXMLSchema();
            byte[] byteArray = Encoding.UTF8.GetBytes(xmlSchemaString);
            MemoryStream stream = new MemoryStream(byteArray);
            XmlReader reader = XmlReader.Create(stream);
            schema = xs.Add("http://www.contoso.com/books", reader);
        }
        else
        {
            return null;
        }

    }
    return schema;
}

//************************************************************************************ 
// 
//  Helper method to validate the XML against the schema. 
// 
//************************************************************************************ 
private void validateXML(bool generateSchema, XmlDocument doc)
{
    if (doc.Schemas.Count == 0)
    {
        // Helper method to retrieve schema.
        XmlSchema schema = getSchema(generateSchema);
        doc.Schemas.Add(schema);
    }

    // Use an event handler to validate the XML node against the schema.
    doc.Validate(settings_ValidationEventHandler);

}

//************************************************************************************ 
// 
//  Event handler that is raised when XML doesn't validate against the schema. 
// 
//************************************************************************************ 
void settings_ValidationEventHandler(object sender,
    System.Xml.Schema.ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
    {
        System.Windows.Forms.MessageBox.Show
            ("The following validation warning occurred: " + e.Message);
    }
    else if (e.Severity == XmlSeverityType.Error)
    {
        System.Windows.Forms.MessageBox.Show
            ("The following critical validation errors occurred: " + e.Message);
        Type objectType = sender.GetType();
    }

}
//************************************************************************************ 
// 
//  Associate the schema with XML. Then, load the XML and validate it against 
//  the schema. 
// 
//************************************************************************************

XmlDocument ^XMLDOMProcessing::XMLHelperMethods::LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
	XmlReader ^reader;

	XmlReaderSettings ^settings = gcnew XmlReaderSettings();

	// Helper method to retrieve schema.
	XmlSchema ^schema = getSchema(generateSchema);
	
	if (schema == nullptr)
	{
		return nullptr;
	}

	settings->Schemas->Add(schema);
	settings->ValidationEventHandler +=
		gcnew System::Xml::Schema::ValidationEventHandler
		(this, &XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler);
	settings->ValidationFlags = settings->ValidationFlags | XmlSchemaValidationFlags::ReportValidationWarnings;
	settings->ValidationType = ValidationType::Schema;

	try
	{
		reader = XmlReader::Create("booksData.xml", settings);
	}
	catch (System::IO::FileNotFoundException ^e1)
	{
		if (generateXML)
		{
			String ^xml = generateXMLString();
			array<Byte> ^byteArray = Encoding::UTF8->GetBytes(xml);
			MemoryStream ^stream = gcnew MemoryStream(byteArray);
			reader = XmlReader::Create(stream, settings);
		}
		else
		{
			return nullptr;
		}

	}

	XmlDocument ^doc = gcnew XmlDocument();
	doc->PreserveWhitespace = true;
	doc->Load(reader);
	reader->Close();

	return doc;
}

//************************************************************************************ 
// 
//  Helper method that generates an XML Schema. 
// 
//************************************************************************************

String ^XMLDOMProcessing::XMLHelperMethods::generateXMLSchema()
{
	String ^xmlSchema = "<?xml version=\"1.0\" encoding=\"utf-8\"?> " + 
		"<xs:schema attributeFormDefault=\"unqualified\" " + 
		"elementFormDefault=\"qualified\" targetNamespace=\"http://www.contoso.com/books\" " + 
		"xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"> " + "<xs:element name=\"books\"> " + 
		"<xs:complexType> " + "<xs:sequence> " + "<xs:element maxOccurs=\"unbounded\" name=\"book\"> " + 
		"<xs:complexType> " + "<xs:sequence> " + "<xs:element name=\"title\" type=\"xs:string\" /> " + 
		"<xs:element name=\"price\" type=\"xs:decimal\" /> " + "</xs:sequence> " + 
		"<xs:attribute name=\"genre\" type=\"xs:string\" use=\"required\" /> " + 
		"<xs:attribute name=\"publicationdate\" type=\"xs:date\" use=\"required\" /> " + 
		"<xs:attribute name=\"ISBN\" type=\"xs:string\" use=\"required\" /> " + "</xs:complexType> " + 
		"</xs:element> " + "</xs:sequence> " + "</xs:complexType> " + "</xs:element> " + "</xs:schema> ";
	
	return xmlSchema;
}

//************************************************************************************ 
// 
//  Helper method that gets a schema 
// 
//************************************************************************************

XmlSchema ^XMLDOMProcessing::XMLHelperMethods::getSchema(bool generateSchema)
{
	XmlSchemaSet ^xs = gcnew XmlSchemaSet();
	XmlSchema ^schema;
	try
	{
		schema = xs->Add("http://www.contoso.com/books", "booksData.xsd");
	}
	catch (System::IO::FileNotFoundException ^e1)
	{
		if (generateSchema)
		{
			String ^xmlSchemaString = generateXMLSchema();
			array<Byte> ^byteArray = Encoding::UTF8->GetBytes(xmlSchemaString);
			MemoryStream ^stream = gcnew MemoryStream(byteArray);
			XmlReader ^reader = XmlReader::Create(stream);
			schema = xs->Add("http://www.contoso.com/books", reader);
		}
		else
		{
			return nullptr;
		}

	}
	return schema;
}
//************************************************************************************ 
// 
//  Helper method to validate the XML against the schema. 
// 
//************************************************************************************ 
bool XMLDOMProcessing::XMLHelperMethods::validateXML(bool generateSchema, XmlDocument ^doc)
{
	if (doc->Schemas->Count == 0)
	{
		// Helper method to retrieve schema.
		XmlSchema ^schema = getSchema(generateSchema);
		doc->Schemas->Add(schema);
	}

	ValidationEventHandler^ eventHandler = gcnew System::Xml::Schema::ValidationEventHandler
		(this, &XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler);

	// Use an event handler to validate the XML node against the schema.
	doc->Validate(eventHandler);

	if (_IsValid == false)
	{
		_IsValid = true;
		return false;
	}
	else
	{
		return true;
	}

}
//************************************************************************************ 
// 
//  Event handler that is raised when XML doesn't validate against the schema. 
// 
//************************************************************************************ 

void XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler(System::Object ^sender, System::Xml::Schema::ValidationEventArgs ^e)
{
	if (e->Severity == XmlSeverityType::Warning)
	{
		// do nothing.
	}
	else if (e->Severity == XmlSeverityType::Error)
	{
		// set some global variables.
		_IsValid = false;
		ValidationError = e->Message;
	}
}

Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Learn more: Validating an XML Document in the DOM

Navigate the document tree

You can use properties to navigate around an XML document. But before you use any of them, let’s quickly review a few terms. Your document is composed of nodes. Each node has as single parent node directly above it. The only node that does not have a parent node is the document root, as it is the top-level node. Most nodes can have child nodes, which are nodes directly below them. Nodes that are at the same level are siblings.

The following examples, show you how to obtain the root node, jump to the first child node of the root node, access any of its child nodes, get back out to the parent node, and then navigate across sibling nodes.

Start with the root node

This example gets the root node and then uses that node to output the contents of the document to the console.

Option Strict
Option Explicit

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()
        'Create the XmlDocument. 
        Dim doc As New XmlDocument()
        doc.LoadXml("<?xml version='1.0' ?>" & _
                    "<book genre='novel' ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "</book>")

        'Display the document element.
        Console.WriteLine(doc.DocumentElement.OuterXml)
    End Sub 'Main
End Class 'Sample
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<?xml version='1.0' ?>" +
                "<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "</book>");

    //Display the document element.
    Console.WriteLine(doc.DocumentElement.OuterXml);
 }
}
#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{

   //Create the XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( "<?xml version='1.0' ?><book genre='novel' ISBN='1-861001-57-5'><title>Pride And Prejudice</title></book>" );

   //Display the document element.
   Console::WriteLine( doc->DocumentElement->OuterXml );
}

Get child nodes

This example jumps to the first child node of the root node and then iterates through the child nodes of that node if any exist.

Option Strict
Option Explicit

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()

        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "<price>19.95</price>" & _
                    "</book>")

        Dim root As XmlNode = doc.FirstChild

        'Display the contents of the child nodes. 
        If root.HasChildNodes Then 
            Dim i As Integer 
            For i = 0 To root.ChildNodes.Count - 1
                Console.WriteLine(root.ChildNodes(i).InnerText)
            Next i
        End If 
    End Sub 'Main
End Class 'Sample
using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "<price>19.95</price>" +
                "</book>");

    XmlNode root = doc.FirstChild;

    //Display the contents of the child nodes. 
    if (root.HasChildNodes)
    {
      for (int i=0; i<root.ChildNodes.Count; i++)
      {
        Console.WriteLine(root.ChildNodes[i].InnerText);
      }
    }
  }
}
#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( "<book ISBN='1-861001-57-5'>" 
   "<title>Pride And Prejudice</title>" 
   "<price>19.95</price>" 
   "</book>" );
   XmlNode^ root = doc->FirstChild;

   //Display the contents of the child nodes. 
   if ( root->HasChildNodes )
   {
      for ( int i = 0; i < root->ChildNodes->Count; i++ )
      {
         Console::WriteLine( root->ChildNodes[ i ]->InnerText );
      }
   }
}

Get back to the parent node

Use the ParentNode property.

Jump to the last child node

This example gets to the price of a book which is the last child node of a book node.

Option Explicit
Option Strict

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()

        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "<price>19.95</price>" & _
                    "</book>")

        Dim root As XmlNode = doc.FirstChild

        Console.WriteLine("Display the price element...")
        Console.WriteLine(root.LastChild.OuterXml)
    End Sub 'Main
End Class 'Sample
using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "<price>19.95</price>" +
                "</book>");

    XmlNode root = doc.FirstChild;

    Console.WriteLine("Display the price element...");
    Console.WriteLine(root.LastChild.OuterXml);
  }
}
#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( "<book ISBN='1-861001-57-5'>" 
   "<title>Pride And Prejudice</title>" 
   "<price>19.95</price>" 
   "</book>" );
   XmlNode^ root = doc->FirstChild;
   Console::WriteLine( "Display the price element..." );
   Console::WriteLine( root->LastChild->OuterXml );
}

Navigate forward across siblings

This example moves forward from book to book. Book nodes are siblings to one another.

Imports System
Imports System.Xml
Imports Microsoft.VisualBasic

public class Sample 

  public shared sub Main() 

      Dim doc as XmlDocument = new XmlDocument()
      doc.Load("books.xml")

      Dim currNode as XmlNode = doc.DocumentElement.FirstChild
      Console.WriteLine("First book...")
      Console.WriteLine(currNode.OuterXml)

      Dim nextNode as XmlNode = currNode.NextSibling
      Console.WriteLine(ControlChars.LF + "Second book...")
      Console.WriteLine(nextNode.OuterXml) 

  end sub
end class
using System;
using System.Xml;

public class Sample {

  public static void Main() {

      XmlDocument doc = new XmlDocument();
      doc.Load("books.xml");

      XmlNode currNode = doc.DocumentElement.FirstChild;
      Console.WriteLine("First book...");
      Console.WriteLine(currNode.OuterXml);

      XmlNode nextNode = currNode.NextSibling;
      Console.WriteLine("\r\nSecond book...");
      Console.WriteLine(nextNode.OuterXml); 

  }
}
#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "books.xml" );
   XmlNode^ currNode = doc->DocumentElement->FirstChild;
   Console::WriteLine( "First book..." );
   Console::WriteLine( currNode->OuterXml );
   XmlNode^ nextNode = currNode->NextSibling;
   Console::WriteLine( "\r\nSecond book..." );
   Console::WriteLine( nextNode->OuterXml );
}

Navigate backwards across siblings

This example moves backwards from book to book.

Imports System
Imports System.Xml
Imports Microsoft.VisualBasic

public class Sample 

  public shared sub Main() 

      Dim doc as XmlDocument = new XmlDocument()
      doc.Load("books.xml")

      Dim lastNode as XmlNode = doc.DocumentElement.LastChild
      Console.WriteLine("Last book...")
      Console.WriteLine(lastNode.OuterXml)

      Dim prevNode as XmlNode = lastNode.PreviousSibling
      Console.WriteLine(ControlChars.LF + "Previous book...")
      Console.WriteLine(prevNode.OuterXml)  
  end sub
end class
using System;
using System.Xml;

public class Sample {

  public static void Main() {

      XmlDocument doc = new XmlDocument();
      doc.Load("books.xml");

      XmlNode lastNode = doc.DocumentElement.LastChild;
      Console.WriteLine("Last book...");
      Console.WriteLine(lastNode.OuterXml);

      XmlNode prevNode = lastNode.PreviousSibling;
      Console.WriteLine("\r\nPrevious book...");
      Console.WriteLine(prevNode.OuterXml);  
  }
}
#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "books.xml" );
   XmlNode^ lastNode = doc->DocumentElement->LastChild;
   Console::WriteLine( "Last book..." );
   Console::WriteLine( lastNode->OuterXml );
   XmlNode^ prevNode = lastNode->PreviousSibling;
   Console::WriteLine( "\r\nPrevious book..." );
   Console::WriteLine( prevNode->OuterXml );
}

Find nodes

The most popular way to find one or more nodes of data is to use an XPath query string, but there are also methods that don’t require one.

Get a single node

This example locates a book by using the ISBN number.

Public Function GetBook(ByVal uniqueAttribute As String, ByVal doc As XmlDocument) As XmlNode
    Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
    nsmgr.AddNamespace("bk", "http://www.contoso.com/books")
    Dim xPathString As String = ("//bk:books/bk:book[@ISBN='" _
                & (uniqueAttribute & "']"))
    Dim xmlNode As XmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr)
    Return xmlNode
End Function
public XmlNode GetBook(string uniqueAttribute, XmlDocument doc)
{
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("bk", "http://www.contoso.com/books");
    string xPathString = "//bk:books/bk:book[@ISBN='" + uniqueAttribute + "']";
    XmlNode xmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr);
   return xmlNode;
}
XmlNode ^XMLDOMProcessing::XMLHelperMethods::GetBook(String ^uniqueAttribute, XmlDocument ^doc)
{
	XmlNamespaceManager ^nsmgr = gcnew XmlNamespaceManager(doc->NameTable);
	nsmgr->AddNamespace("bk", "http://www.contoso.com/books");
	String ^xPathString = "//bk:books/bk:book[@ISBN='" + uniqueAttribute + "']";
	XmlNode ^xmlNode = doc->DocumentElement->SelectSingleNode(xPathString, nsmgr);
	return xmlNode;
}

The string used in this example is an Xpath query. You can find more examples of them here: XPath examples.

You can also use the GetElementById to retrieve nodes. To use this approach, you’ll have to define ID’s in the document type definition declarations of your XML file.

After you get a node, you get the value of attributes or child nodes. This example does that with a book node.

Public Sub GetBookInformation(ByRef title As String, ByRef ISBN As String, ByRef publicationDate As String, ByRef price As String, ByRef genre As String, ByVal book As XmlNode)
    Dim bookElement As XmlElement = CType(book, XmlElement)
    ' Get the attributes of a book.         
    Dim attr As XmlAttribute = bookElement.GetAttributeNode("ISBN")
    ISBN = attr.InnerXml
    attr = bookElement.GetAttributeNode("genre")
    genre = attr.InnerXml
    attr = bookElement.GetAttributeNode("publicationdate")
    publicationDate = attr.InnerXml
    ' Get the values of child elements of a book.
    title = bookElement("title").InnerText
    price = bookElement("price").InnerText
End Sub
public void GetBookInformation(ref string title, ref string ISBN, ref string publicationDate,
    ref string price, ref string genre, XmlNode book)
{
    XmlElement bookElement = (XmlElement)book;

    // Get the attributes of a book.        
    XmlAttribute attr = bookElement.GetAttributeNode("ISBN");
    ISBN = attr.InnerXml;

    attr = bookElement.GetAttributeNode("genre");
    genre = attr.InnerXml;

    attr = bookElement.GetAttributeNode("publicationdate");
    publicationDate = attr.InnerXml;

    // Get the values of child elements of a book.
    title = bookElement["title"].InnerText;
    price = bookElement["price"].InnerText;
}
void XMLDOMProcessing::XMLHelperMethods::GetBookInformation
(String ^%title, String ^%ISBN, String ^%publicationDate, String ^%price, String ^%genre, XmlNode ^book)
{
	XmlElement ^bookElement = safe_cast<XmlElement^>(book);

	// Get the attributes of a book.        
	XmlAttribute ^attr = bookElement->GetAttributeNode("ISBN");
	ISBN = attr->InnerXml;

	attr = bookElement->GetAttributeNode("genre");
	genre = attr->InnerXml;

	attr = bookElement->GetAttributeNode("publicationdate");
	publicationDate = attr->InnerXml;

	// Get the values of child elements of a book.
	title = bookElement["title"]->InnerText;
	price = bookElement["price"]->InnerText;
}

Get a collection of nodes

This example selects all books where the author's last name is Austen, and then changes the price of those books.

Imports System
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()

    'Create the XmlDocument. 
    Dim doc as XmlDocument = new XmlDocument()
    doc.Load("booksort.xml")

    Dim book as XmlNode
    Dim nodeList as XmlNodeList 
    Dim root as XmlNode = doc.DocumentElement

    nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']")

    'Change the price on the books.
    for each book in nodeList      
      book.LastChild.InnerText="15.95"
    next 

    Console.WriteLine("Display the modified XML document....")
    doc.Save(Console.Out)

  end sub
end class
using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

    XmlDocument doc = new XmlDocument();
    doc.Load("booksort.xml");

    XmlNodeList nodeList;
    XmlNode root = doc.DocumentElement;

    nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']");

    //Change the price on the books. 
    foreach (XmlNode book in nodeList)
    {
      book.LastChild.InnerText="15.95";
    }

    Console.WriteLine("Display the modified XML document....");
    doc.Save(Console.Out);

  }
}
#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "booksort.xml" );
   XmlNodeList^ nodeList;
   XmlNode^ root = doc->DocumentElement;
   nodeList = root->SelectNodes( "descendant::book[author/last-name='Austen']" );

   //Change the price on the books.
   System::Collections::IEnumerator^ myEnum = nodeList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      XmlNode^ book = safe_cast<XmlNode^>(myEnum->Current);
      book->LastChild->InnerText = "15.95";
   }

   Console::WriteLine( "Display the modified XML document...." );
   doc->Save( Console::Out );
}

You can also get a collection of nodes by using the name of the node. For example, this example gets a collection of all book titles.

Option Explicit
Option Strict

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()
        'Create the XmlDocument. 
        Dim doc As New XmlDocument()
        doc.Load("books.xml")

        'Display all the book titles. 
        Dim elemList As XmlNodeList = doc.GetElementsByTagName("title")
        Dim i As Integer 
        For i = 0 To elemList.Count - 1
            Console.WriteLine(elemList(i).InnerXml)
        Next i
    End Sub 'Main 
End Class 'Sample
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.Load("books.xml");

    //Display all the book titles.
    XmlNodeList elemList = doc.GetElementsByTagName("title");
    for (int i=0; i < elemList.Count; i++)
    {   
      Console.WriteLine(elemList[i].InnerXml);
    }  

  }
}
#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "books.xml" );

   //Display all the book titles.
   XmlNodeList^ elemList = doc->GetElementsByTagName( "title" );
   for ( int i = 0; i < elemList->Count; i++ )
   {
      Console::WriteLine( elemList[ i ]->InnerXml );
   }
}

Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Learn more: Select Nodes Using XPath Navigation

Edit nodes

This example edits a book node and its attributes.

Public Sub editBook(ByVal title As String, ByVal ISBN As String,
                    ByVal publicationDate As String, ByVal genre As String,
                    ByVal price As String, ByVal book As XmlNode, ByVal validateNode As Boolean,
                    ByVal generateSchema As Boolean)

    Dim bookElement As XmlElement = CType(book, XmlElement)

    ' Get the attributes of a book.        
    bookElement.SetAttribute("ISBN", ISBN)
    bookElement.SetAttribute("genre", genre)
    bookElement.SetAttribute("publicationdate", publicationDate)

    ' Get the values of child elements of a book.
    bookElement("title").InnerText = title
    bookElement("price").InnerText = price
    If validateNode Then
        validateXML(generateSchema, bookElement.OwnerDocument)
    End If 

End Sub
public void editBook(string title, string ISBN, string publicationDate,
    string genre, string price, XmlNode book, bool validateNode, bool generateSchema)
{

    XmlElement bookElement = (XmlElement)book;

    // Get the attributes of a book.        
    bookElement.SetAttribute("ISBN", ISBN);
    bookElement.SetAttribute("genre", genre);
    bookElement.SetAttribute("publicationdate", publicationDate);

    // Get the values of child elements of a book.
    bookElement["title"].InnerText = title;
    bookElement["price"].InnerText = price;

    if (validateNode)
    {
        validateXML(generateSchema, bookElement.OwnerDocument);
    }
}
bool XMLDOMProcessing::XMLHelperMethods::editBook(String ^title, String ^ISBN, String ^publicationDate, String ^genre, String ^price, XmlNode ^book, bool validateNode, bool generateSchema)
{

	XmlElement ^bookElement = safe_cast<XmlElement^>(book);

	// Get the attributes of a book.        
	bookElement->SetAttribute("ISBN", ISBN);
	bookElement->SetAttribute("genre", genre);
	bookElement->SetAttribute("publicationdate", publicationDate);

	// Get the values of child elements of a book.
	bookElement["title"]->InnerText = title;
	bookElement["price"]->InnerText = price;

	if (validateNode)
	{
		if (validateXML(generateSchema, bookElement->OwnerDocument))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	return true;
}

Learn more: Modifying Nodes, Content, and Values in an XML Document

Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Add nodes

To add a node, use the CreateElement method or the CreateNode method.

To add a data node such as a book, use the CreateElement method.

For any other type of node such as a comment, whitespace node, or CDATA node, use the CreateNode method.

This example creates a book node, adds attrubutes to that node, and then adds that node to the document.

Public Function AddNewBook(ByVal genre As String, ByVal ISBN As String, ByVal misc As String, ByVal title As String, ByVal price As String, ByVal doc As XmlDocument) As XmlElement
    ' Create a new book element. 
    Dim bookElement As XmlElement = doc.CreateElement("book", "http://www.contoso.com/books")

    ' Create attributes for book and append them to the book element. 
    Dim attribute As XmlAttribute = doc.CreateAttribute("genre")
    attribute.Value = genre
    bookElement.Attributes.Append(attribute)

    attribute = doc.CreateAttribute("ISBN")
    attribute.Value = ISBN
    bookElement.Attributes.Append(attribute)

    attribute = doc.CreateAttribute("publicationdate")
    attribute.Value = misc
    bookElement.Attributes.Append(attribute)

    ' Create and append a child element for the title of the book. 
    Dim titleElement As XmlElement = doc.CreateElement("title")
    titleElement.InnerText = title
    bookElement.AppendChild(titleElement)

    ' Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml = bookElement.InnerXml.Replace(titleElement.OuterXml, _
                           "\n   " & titleElement.OuterXml & " " & ControlChars.NewLine + "    ")
    ' Create and append a child element for the price of the book. 
    Dim priceElement As XmlElement = doc.CreateElement("price")
    priceElement.InnerText = price
    bookElement.AppendChild(priceElement)

    ' Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml = bookElement.InnerXml.Replace(priceElement.OuterXml,
                                                        (priceElement.OuterXml & "   " & ControlChars.NewLine & "  "))
    Return bookElement
End Function
public XmlElement AddNewBook(string genre, string ISBN, string misc, 
    string title, string price, XmlDocument doc)
{
    // Create a new book element.
    XmlElement bookElement = doc.CreateElement("book", "http://www.contoso.com/books");

    // Create attributes for book and append them to the book element.
    XmlAttribute attribute = doc.CreateAttribute("genre");
    attribute.Value = genre;
    bookElement.Attributes.Append(attribute);

    attribute = doc.CreateAttribute("ISBN");
    attribute.Value = ISBN;
    bookElement.Attributes.Append(attribute);

    attribute = doc.CreateAttribute("publicationdate");
    attribute.Value = misc;
    bookElement.Attributes.Append(attribute);

    // Create and append a child element for the title of the book.
    XmlElement titleElement = doc.CreateElement("title");
    titleElement.InnerText = title;
    bookElement.AppendChild(titleElement);

    // Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml = 
        bookElement.InnerXml.Replace(titleElement.OuterXml, 
        "\n    " + titleElement.OuterXml + " \n    ");

    // Create and append a child element for the price of the book.
    XmlElement priceElement = doc.CreateElement("price");
    priceElement.InnerText= price;
    bookElement.AppendChild(priceElement);

    // Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml =
        bookElement.InnerXml.Replace(priceElement.OuterXml, priceElement.OuterXml + "   \n  ");

    return bookElement;

}
XmlElement ^XMLDOMProcessing::XMLHelperMethods::AddNewBook(String ^genre, String ^ISBN, String ^misc, String ^title, String ^price, XmlDocument ^doc)
{
	// Create a new book element.
	XmlElement ^bookElement = doc->CreateElement("book", "http://www.contoso.com/books");

	// Create attributes for book and append them to the book element.
	XmlAttribute ^attribute = doc->CreateAttribute("genre");
	attribute->Value = genre;
	bookElement->Attributes->Append(attribute);

	attribute = doc->CreateAttribute("ISBN");
	attribute->Value = ISBN;
	bookElement->Attributes->Append(attribute);

	attribute = doc->CreateAttribute("publicationdate");
	attribute->Value = misc;
	bookElement->Attributes->Append(attribute);

	// Create and append a child element for the title of the book.
	XmlElement ^titleElement = doc->CreateElement("title");
	titleElement->InnerText = title;
	bookElement->AppendChild(titleElement);

	// Introduce a newline character so that XML is nicely formatted.
	bookElement->InnerXml = bookElement->InnerXml->Replace(titleElement->OuterXml, "\n    " + titleElement->OuterXml + " \n    ");

	// Create and append a child element for the price of the book.
	XmlElement ^priceElement = doc->CreateElement("price");
	priceElement->InnerText = price;
	bookElement->AppendChild(priceElement);

	// Introduce a newline character so that XML is nicely formatted.
	bookElement->InnerXml = bookElement->InnerXml->Replace(priceElement->OuterXml, priceElement->OuterXml + "   \n  ");

	return bookElement;

}

Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Learn more: Inserting Nodes into an XML Document

Remove nodes

To remove a node, use the RemoveChild method.

This example removes a book from the document and any whitespace that appears just before the book node.

Public Sub deleteBook(ByVal book As XmlNode)

    Dim prevNode As XmlNode = book.PreviousSibling
    book.OwnerDocument.DocumentElement.RemoveChild(book)

    If ((prevNode.NodeType = XmlNodeType.Whitespace) _
                OrElse (prevNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
        prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode)

    End If 
End Sub
public void deleteBook(XmlNode book)
{
    XmlNode prevNode = book.PreviousSibling;

    book.OwnerDocument.DocumentElement.RemoveChild(book);


    if (prevNode.NodeType == XmlNodeType.Whitespace || 
        prevNode.NodeType == XmlNodeType.SignificantWhitespace)
    {
        prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode);
    }
}
void XMLDOMProcessing::XMLHelperMethods::deleteBook(XmlNode ^book)
{
	XmlNode ^prevNode = book->PreviousSibling;

	book->OwnerDocument->DocumentElement->RemoveChild(book);


	if (prevNode->NodeType == XmlNodeType::Whitespace || prevNode->NodeType == XmlNodeType::SignificantWhitespace)
	{
		prevNode->OwnerDocument->DocumentElement->RemoveChild(prevNode);
	}
}

Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Learn more: Removing Nodes, Content, and Values from an XML Document

Position nodes

You can choose where you want a node to appear in your document by using the InsertBefore and InsertAfter methods.

This example shows two helper methods. One of them moves a node higher in a list. The other one moves a node lower.

These methods could be used in an application that enables users to move books up and down in a list of books. When a user chooses a book and presses an up or down button, your code could call methods like these to position the corresponding book node before or after other book nodes.

'************************************************************************************ 
' 
'  Summary: Move elements up in the XML. 
'   
' 
'************************************************************************************ 
Public Sub MoveElementUp(ByVal book As XmlNode)
    Dim previousNode As XmlNode = book.PreviousSibling

    While ((Not (previousNode) Is Nothing) _
                AndAlso (previousNode.NodeType <> XmlNodeType.Element))
        previousNode = previousNode.PreviousSibling

    End While 
    If (Not (previousNode) Is Nothing) Then 
        Dim newLineNode As XmlNode = book.NextSibling
        book.OwnerDocument.DocumentElement.RemoveChild(book)

        If ((newLineNode.NodeType = XmlNodeType.Whitespace) _
                    Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode)
        End If

        InsertBookElement(CType(book, XmlElement), Constants.positionAbove,
                          previousNode, False, False)
    End If 
End Sub 

'************************************************************************************ 
' 
'  Summary: Move elements down in the XML. 
'   
' 
'************************************************************************************ 
Public Sub MoveElementDown(ByVal book As XmlNode)
    ' Walk backwards until we find an element - ignore text nodes 
    Dim NextNode As XmlNode = book.NextSibling

    While ((Not (NextNode) Is Nothing) _
                AndAlso (NextNode.NodeType <> XmlNodeType.Element))
        NextNode = NextNode.NextSibling

    End While 

    If (Not (NextNode) Is Nothing) Then 
        Dim newLineNode As XmlNode = book.PreviousSibling
        book.OwnerDocument.DocumentElement.RemoveChild(book)

        If ((newLineNode.NodeType = XmlNodeType.Whitespace) _
                    Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode)
        End If

        InsertBookElement(CType(book, XmlElement), Constants.positionBelow,
                          NextNode, False, False)
    End If 
End Sub
//************************************************************************************ 
// 
//  Summary: Move elements up in the XML. 
//   
// 
//************************************************************************************ 

public void MoveElementUp(XmlNode book)
{
    XmlNode previousNode = book.PreviousSibling;
    while (previousNode != null && (previousNode.NodeType != XmlNodeType.Element))
    {
        previousNode = previousNode.PreviousSibling;
    }
    if (previousNode != null)
    {
        XmlNode newLineNode = book.NextSibling;
        book.OwnerDocument.DocumentElement.RemoveChild(book);
        if (newLineNode.NodeType == XmlNodeType.Whitespace | 
            newLineNode.NodeType == XmlNodeType.SignificantWhitespace)
        {
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode);
        }
        InsertBookElement((XmlElement)book, Constants.positionAbove, 
            previousNode, false, false);
    }
}


//************************************************************************************ 
// 
//  Summary: Move elements down in the XML. 
//   
// 
//************************************************************************************ 
public void MoveElementDown(XmlNode book)
{
    // Walk backwards until we find an element - ignore text nodes
    XmlNode NextNode = book.NextSibling;
    while (NextNode != null && (NextNode.NodeType != XmlNodeType.Element))
    {
        NextNode = NextNode.NextSibling;
    }
    if (NextNode != null)
    {
        XmlNode newLineNode = book.PreviousSibling;
        book.OwnerDocument.DocumentElement.RemoveChild(book);
        if (newLineNode.NodeType == XmlNodeType.Whitespace |
            newLineNode.NodeType == XmlNodeType.SignificantWhitespace)
        {
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode);
        }

        InsertBookElement((XmlElement)book, Constants.positionBelow, 
            NextNode, false, false);
    }

}
//************************************************************************************ 
// 
//  Summary: Move elements up in the XML. 
//   
// 
//************************************************************************************ 
void XMLDOMProcessing::XMLHelperMethods::MoveElementUp(XmlNode ^book)
{
	XmlNode ^previousNode = book->PreviousSibling;
	while (previousNode != nullptr && (previousNode->NodeType != XmlNodeType::Element))
	{
		previousNode = previousNode->PreviousSibling;
	}
	if (previousNode != nullptr)
	{
		XmlNode ^newLineNode = book->NextSibling;
		book->OwnerDocument->DocumentElement->RemoveChild(book);
		if (newLineNode->NodeType == XmlNodeType::Whitespace || newLineNode->NodeType == XmlNodeType::SignificantWhitespace)
		{
			newLineNode->OwnerDocument->DocumentElement->RemoveChild(newLineNode);
		}
		InsertBookElement(safe_cast<XmlElement^>(book), Constants::positionAbove, previousNode, false, false);
	}
}

//************************************************************************************ 
// 
//  Summary: Move elements down in the XML. 
//   
// 
//************************************************************************************ 
void XMLDOMProcessing::XMLHelperMethods::MoveElementDown(XmlNode ^book)
{
	// Walk backwards until we find an element - ignore text nodes
	XmlNode ^NextNode = book->NextSibling;
	while (NextNode != nullptr && (NextNode->NodeType != XmlNodeType::Element))
	{
		NextNode = NextNode->NextSibling;
	}
	if (NextNode != nullptr)
	{
		XmlNode ^newLineNode = book->PreviousSibling;
		book->OwnerDocument->DocumentElement->RemoveChild(book);
		if (newLineNode->NodeType == XmlNodeType::Whitespace || newLineNode->NodeType == XmlNodeType::SignificantWhitespace)
		{
			newLineNode->OwnerDocument->DocumentElement->RemoveChild(newLineNode);
		}

		InsertBookElement(safe_cast<XmlElement^>(book), Constants::positionBelow, NextNode, false, false);
	}

}

Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

Version Information

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.