XmlDocument::Validate Method (ValidationEventHandler)

Validates the XmlDocument against the XML Schema Definition Language (XSD) schemas contained in the Schemas property.

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

public:
void Validate(
	ValidationEventHandler^ validationEventHandler
)

Parameters

validationEventHandler
Type: System.Xml.Schema::ValidationEventHandler

The ValidationEventHandler object that receives information about schema validation warnings and errors.

ExceptionCondition
XmlSchemaValidationException

A schema validation event occurred and no ValidationEventHandler object was specified.

The Validate method validates the XML data in the XmlDocument against the schemas contained in the Schemas property. The Validate method performs infoset augmentation. Specifically, after successful validation, schema defaults are applied, text values are converted to atomic values as necessary, and type information is associated with validated information items. The result is a previously un-typed XML sub-tree in the XmlDocument replaced with a typed sub-tree.

The following are important notes to consider when using the Validate method.

  • Schema location hints like xsi:schemaLocation or xsi:noNamespaceSchemaLocation are ignored.

  • Inline schemas are ignored.

  • If schema validation errors occur during validation the XmlDocument becomes partially validated with some nodes with correct type information and some without.

  • The validation process includes checking for uniqueness and reference constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, and xs:unique).

The following example illustrates use of the Validate method. The example creates an XmlDocument that contains an associated XSD schema using the XmlReaderSettings and XmlReader objects. The example then uses the XPathNavigator class to incorrectly modify the typed value of an element in the XML document generating a schema validation error.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;
using namespace System::Xml::XPath;

class XPathValidation
{
public:

    static void Main()
    {
        try
        {
            XmlReaderSettings^ settings = gcnew XmlReaderSettings();
            settings->Schemas->Add("http://www.contoso.com/books", "contosoBooks.xsd");
            settings->ValidationType = ValidationType::Schema;

            XmlReader^ reader = XmlReader::Create("contosoBooks.xml", settings);
            XmlDocument^ document = gcnew XmlDocument();
            document->Load(reader);

            ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(ValidationEventHandlerOne);

            // the following call to Validate succeeds.
            document->Validate(eventHandler);

            // add a node so that the document is no longer valid
            XPathNavigator^ navigator = document->CreateNavigator();
            navigator->MoveToFollowing("price", "http://www.contoso.com/books");
            XmlWriter^ writer = navigator->InsertAfter();
            writer->WriteStartElement("anotherNode", "http://www.contoso.com/books");
            writer->WriteEndElement();
            writer->Close();

            // the document will now fail to successfully validate
            document->Validate(eventHandler);
        }
        catch(Exception^ ex)
        {
            Console::WriteLine(ex->Message);
        }
    }

    static void ValidationEventHandlerOne(Object^ sender, ValidationEventArgs^ e)
    {
        switch (e->Severity)
        {
        case XmlSeverityType::Error:
            Console::WriteLine("Error: {0}", e->Message);
            break;
        case XmlSeverityType::Warning:
            Console::WriteLine("Warning {0}", e->Message);
            break;
        }

    }
};

int main()
{
    XPathValidation::Main();
    Console::ReadLine();
    return 0;
};

The example takes the contosoBooks.xml and contosoBooks.xsd files as input.

<?xml version="1.0" encoding="utf-8" ?>
<bookstore xmlns="http://www.contoso.com/books">
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
        <author>
            <first-name>Benjamin</first-name>
            <last-name>Franklin</last-name>
        </author>
        <price>8.99</price>
    </book>
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
        <author>
            <first-name>Herman</first-name>
            <last-name>Melville</last-name>
        </author>
        <price>11.99</price>
    </book>
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>
<?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="bookstore">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="unbounded" name="book">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="title" type="xs:string" />
                            <xs:element name="author">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element minOccurs="0" name="name" type="xs:string" />
                                        <xs:element minOccurs="0" name="first-name" type="xs:string" />
                                        <xs:element minOccurs="0" name="last-name" type="xs:string" />
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                            <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>

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft