XmlDocument Constructor

XmlDocument Constructor

Initializes a new instance of the XmlDocument class.

Namespace:  System.Xml
Assembly:  System.Xml (in System.Xml.dll)

public XmlDocument()

The following is an example of load-time validation. A document type definition (DTD) validating XmlReader is passed to the Load method and a ValidationEventHandler is provided to notify users of any validation errors. In this example a validation error is found, but the document is still loaded. Alternatively, you can define a validating XmlReader to throw an exception and stop the load process when a validation error is found by not specifying the ValidationEventHandler. For more information about validating XML data, see the Remarks section of the XmlReader reference page.

using System;
using System.Xml;
using System.Xml.Schema;

namespace Microsoft.Samples.Xml
    sealed class XmlDocumentSample
        private XmlDocumentSample() { }

        static XmlReader reader;
        static String filename = "bookdtd.xml";

        public static void Main()

            ValidationEventHandler eventHandler = new ValidationEventHandler(XmlDocumentSample.ValidationCallback);

                // Create the validating reader and specify DTD validation.
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.DtdProcessing = DtdProcessing.Parse;
                settings.ValidationType = ValidationType.DTD;
                settings.ValidationEventHandler += eventHandler;

                reader = XmlReader.Create(filename, settings);

                // Pass the validating reader to the XML document. 
                // Validation fails due to an undefined attribute, but the  
                // data is still loaded into the document.
                XmlDocument doc = new XmlDocument();
                if (reader != null)

        // Display the validation error. 
        private static void ValidationCallback(object sender, ValidationEventArgs args)
            Console.WriteLine("Validation error loading: {0}", filename);

The example uses the bookDTD.xml file as input.

<!DOCTYPE bookstore [
  <!ELEMENT bookstore (book)*> 
  <!ELEMENT book (title,author,price)>
  <!ELEMENT title (#PCDATA)>
  <!ELEMENT author (#PCDATA)>
  <!ELEMENT price (#PCDATA)>]>
  <book genre="fantasy"  ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>

.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
© 2015 Microsoft