Edit

Share via


XmlSchemaValidator Push-Based Validation

The XmlSchemaValidator class provides an efficient, high-performance mechanism to validate XML data against XML schemas in a push-based manner. For example, the XmlSchemaValidator class allows you to validate an XML infoset in-place without having to serialize it as an XML document and then reparse the document using a validating XML reader.

The XmlSchemaValidator class can be used in advanced scenarios such as building validation engines over custom XML data sources or as a way to build a validating XML writer.

The following is an example of using the XmlSchemaValidator class to validate the contosoBooks.xml file against the contosoBooks.xsd schema. The example uses the XmlSerializer class to deserialize the contosoBooks.xml file and pass the value of the nodes to the methods of the XmlSchemaValidator class.

Note

This example is used throughout the sections of this topic.

using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Collections;

namespace Microsoft.Samples.Xml.Schema
{
    class XmlSchemaValidatorExamples
    {
        static void Main()
        {
            // The XML document to deserialize into the XmlSerializer object.
            XmlReader reader = XmlReader.Create("contosoBooks.xml");

            // The XmlSerializer object.
            XmlSerializer serializer = new XmlSerializer(typeof(ContosoBooks));
            ContosoBooks books = (ContosoBooks)serializer.Deserialize(reader);

            // The XmlSchemaSet object containing the schema used to validate the XML document.
            XmlSchemaSet schemaSet = new XmlSchemaSet();
            schemaSet.Add("http://www.contoso.com/books", "contosoBooks.xsd");

            // The XmlNamespaceManager object used to handle namespaces.
            XmlNamespaceManager manager = new XmlNamespaceManager(reader.NameTable);

            // Assign a ValidationEventHandler to handle schema validation warnings and errors.
            XmlSchemaValidator validator = new XmlSchemaValidator(reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None);
            validator.ValidationEventHandler += new ValidationEventHandler(SchemaValidationEventHandler);

            // Initialize the XmlSchemaValidator object.
            validator.Initialize();

            // Validate the bookstore element, verify that all required attributes are present
            // and prepare to validate child content.
            validator.ValidateElement("bookstore", "http://www.contoso.com/books", null);
            validator.GetUnspecifiedDefaultAttributes(new ArrayList());
            validator.ValidateEndOfAttributes(null);

            // Get the next expected element in the bookstore context.
            XmlSchemaParticle[] particles = validator.GetExpectedParticles();
            XmlSchemaElement nextElement = particles[0] as XmlSchemaElement;
            Console.WriteLine("Expected Element: '{0}'", nextElement.Name);

            foreach (BookType book in books.Book)
            {
                // Validate the book element.
                validator.ValidateElement("book", "http://www.contoso.com/books", null);

                // Get the expected attributes for the book element.
                Console.Write("\nExpected attributes: ");
                XmlSchemaAttribute[] attributes = validator.GetExpectedAttributes();
                foreach (XmlSchemaAttribute attribute in attributes)
                {
                    Console.Write("'{0}' ", attribute.Name);
                }
                Console.WriteLine();

                // Validate the genre attribute and display its post schema validation information.
                if (book.Genre != null)
                {
                    validator.ValidateAttribute("genre", "", book.Genre, schemaInfo);
                }
                DisplaySchemaInfo();

                // Validate the publicationdate attribute and display its post schema validation information.
                if (book.PublicationDate != null)
                {
                    validator.ValidateAttribute("publicationdate", "", dateTimeGetter(book.PublicationDate), schemaInfo);
                }
                DisplaySchemaInfo();

                // Validate the ISBN attribute and display its post schema validation information.
                if (book.Isbn != null)
                {
                    validator.ValidateAttribute("ISBN", "", book.Isbn, schemaInfo);
                }
                DisplaySchemaInfo();

                // After validating all the attributes for the current element with ValidateAttribute method,
                // you must call GetUnspecifiedDefaultAttributes to validate the default attributes.
                validator.GetUnspecifiedDefaultAttributes(new ArrayList());

                // Verify that all required attributes of the book element are present
                // and prepare to validate child content.
                validator.ValidateEndOfAttributes(null);

                // Validate the title element and its content.
                validator.ValidateElement("title", "http://www.contoso.com/books", null);
                validator.ValidateEndElement(null, book.Title);

                // Validate the author element, verify that all required attributes are present
                // and prepare to validate child content.
                validator.ValidateElement("author", "http://www.contoso.com/books", null);
                validator.GetUnspecifiedDefaultAttributes(new ArrayList());
                validator.ValidateEndOfAttributes(null);

                if (book.Author.Name != null)
                {
                    // Validate the name element and its content.
                    validator.ValidateElement("name", "http://www.contoso.com/books", null);
                    validator.ValidateEndElement(null, book.Author.Name);
                }

                if (book.Author.FirstName != null)
                {
                    // Validate the first-name element and its content.
                    validator.ValidateElement("first-name", "http://www.contoso.com/books", null);
                    validator.ValidateEndElement(null, book.Author.FirstName);
                }

                if (book.Author.LastName != null)
                {
                    // Validate the last-name element and its content.
                    validator.ValidateElement("last-name", "http://www.contoso.com/books", null);
                    validator.ValidateEndElement(null, book.Author.LastName);
                }

                // Validate the content of the author element.
                validator.ValidateEndElement(null);

                // Validate the price element and its content.
                validator.ValidateElement("price", "http://www.contoso.com/books", null);
                validator.ValidateEndElement(null, book.Price);

                // Validate the content of the book element.
                validator.ValidateEndElement(null);
            }

            // Validate the content of the bookstore element.
            validator.ValidateEndElement(null);

            // Close the XmlReader object.
            reader.Close();
        }

        static XmlSchemaInfo schemaInfo = new XmlSchemaInfo();
        static object dateTimeGetterContent;

        static object dateTimeGetterHandle()
        {
            return dateTimeGetterContent;
        }

        static XmlValueGetter dateTimeGetter(DateTime dateTime)
        {
            dateTimeGetterContent = dateTime;
            return new XmlValueGetter(dateTimeGetterHandle);
        }

        static void DisplaySchemaInfo()
        {
            if (schemaInfo.SchemaElement != null)
            {
                Console.WriteLine("Element '{0}' with type '{1}' is '{2}'",
                    schemaInfo.SchemaElement.Name, schemaInfo.SchemaType, schemaInfo.Validity);
            }
            else if (schemaInfo.SchemaAttribute != null)
            {
                Console.WriteLine("Attribute '{0}' with type '{1}' is '{2}'",
                    schemaInfo.SchemaAttribute.Name, schemaInfo.SchemaType, schemaInfo.Validity);
            }
        }

        static void SchemaValidationEventHandler(object sender, ValidationEventArgs e)
        {
            switch (e.Severity)
            {
                case XmlSeverityType.Error:
                    Console.WriteLine("\nError: {0}", e.Message);
                    break;
                case XmlSeverityType.Warning:
                    Console.WriteLine("\nWarning: {0}", e.Message);
                    break;
            }
        }
    }

    [XmlRootAttribute("bookstore", Namespace = "http://www.contoso.com/books", IsNullable = false)]
    public class ContosoBooks
    {
        [XmlElementAttribute("book")]
        public BookType[] Book;
    }

    public class BookType
    {
        [XmlAttributeAttribute("genre")]
        public string Genre;

        [XmlAttributeAttribute("publicationdate", DataType = "date")]
        public DateTime PublicationDate;

        [XmlAttributeAttribute("ISBN")]
        public string Isbn;

        [XmlElementAttribute("title")]
        public string Title;

        [XmlElementAttribute("author")]
        public BookAuthor Author;

        [XmlElementAttribute("price")]
        public Decimal Price;
    }

    public class BookAuthor
    {
        [XmlElementAttribute("name")]
        public string Name;

        [XmlElementAttribute("first-name")]
        public string FirstName;

        [XmlElementAttribute("last-name")]
        public string LastName;
    }
}
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.Serialization
Imports System.Collections


Namespace Microsoft.Samples.Xml.Schema

    Class XmlSchemaValidatorExamples

        Shared Sub Main()

            ' The XML document to deserialize into the XmlSerializer object.
            Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml")

            ' The XmlSerializer object.
            Dim serializer As XmlSerializer = New XmlSerializer(GetType(ContosoBooks))
            Dim books As ContosoBooks = CType(serializer.Deserialize(reader), ContosoBooks)

            ' The XmlSchemaSet object containing the schema used to validate the XML document.
            Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
            schemaSet.Add("http://www.contoso.com/books", "contosoBooks.xsd")

            ' The XmlNamespaceManager object used to handle namespaces.
            Dim manager As XmlNamespaceManager = New XmlNamespaceManager(reader.NameTable)

            ' Assign a ValidationEventHandler to handle schema validation warnings and errors.
            Dim validator As XmlSchemaValidator = New XmlSchemaValidator(reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None)
            'validator.ValidationEventHandler += New ValidationEventHandler(SchemaValidationEventHandler)
            AddHandler validator.ValidationEventHandler, AddressOf SchemaValidationEventHandler

            ' Initialize the XmlSchemaValidator object.
            validator.Initialize()

            ' Validate the bookstore element, verify that all required attributes are present
            ' and prepare to validate child content.
            validator.ValidateElement("bookstore", "http://www.contoso.com/books", Nothing)

            validator.GetUnspecifiedDefaultAttributes(New ArrayList())
            validator.ValidateEndOfAttributes(Nothing)

            ' Get the next expected element in the bookstore context.
            Dim particles() As XmlSchemaParticle = validator.GetExpectedParticles()
            Dim nextElement As XmlSchemaElement = particles(0)
            Console.WriteLine("Expected Element: '{0}'", nextElement.Name)

            For Each book As BookType In books.book
                ' Validate the book element.
                validator.ValidateElement("book", "http://www.contoso.com/books", Nothing)

                ' Get the expected attributes for the book element.
                Console.Write(vbCrLf & "Expected attributes: ")
                Dim attributes() As XmlSchemaAttribute = validator.GetExpectedAttributes()
                For Each attribute As XmlSchemaAttribute In attributes
                    Console.Write("'{0}' ", attribute.Name)
                Next
                Console.WriteLine()

                ' Validate the genre attribute and display its post schema validation information.
                If Not book.Genre Is Nothing Then
                    validator.ValidateAttribute("genre", "", book.Genre, schemaInfo)
                End If
                DisplaySchemaInfo()

                ' Validate the publicationdate attribute and display its post schema validation information.
                If Not book.PublicationDate = Nothing Then
                    validator.ValidateAttribute("publicationdate", "", dateTimeGetter(book.PublicationDate), schemaInfo)
                End If
                DisplaySchemaInfo()

                ' Validate the ISBN attribute and display its post schema validation information.
                If Not book.Isbn Is Nothing Then
                    validator.ValidateAttribute("ISBN", "", book.Isbn, schemaInfo)
                End If
                DisplaySchemaInfo()

                ' After validating all the attributes for the current element with ValidateAttribute method,
                ' you must call GetUnspecifiedDefaultAttributes to validate the default attributes.
                validator.GetUnspecifiedDefaultAttributes(New ArrayList())

                ' Verify that all required attributes of the book element are present
                ' and prepare to validate child content.
                validator.ValidateEndOfAttributes(Nothing)

                ' Validate the title element and its content.
                validator.ValidateElement("title", "http://www.contoso.com/books", Nothing)
                validator.ValidateEndElement(Nothing, book.Title)

                ' Validate the author element, verify that all required attributes are present
                ' and prepare to validate child content.
                validator.ValidateElement("author", "http://www.contoso.com/books", Nothing)

                validator.GetUnspecifiedDefaultAttributes(New ArrayList())
                validator.ValidateEndOfAttributes(Nothing)

                If Not book.Author.Name Is Nothing Then
                    ' Validate the name element and its content.
                    validator.ValidateElement("name", "http://www.contoso.com/books", Nothing)
                    validator.ValidateEndElement(Nothing, book.Author.Name)
                End If

                If Not book.Author.FirstName Is Nothing Then
                    ' Validate the first-name element and its content.
                    validator.ValidateElement("first-name", "http://www.contoso.com/books", Nothing)
                    validator.ValidateEndElement(Nothing, book.Author.FirstName)

                End If

                If Not book.Author.LastName Is Nothing Then
                    ' Validate the last-name element and its content.
                    validator.ValidateElement("last-name", "http://www.contoso.com/books", Nothing)
                    validator.ValidateEndElement(Nothing, book.Author.LastName)
                End If

                ' Validate the content of the author element.
                validator.ValidateEndElement(Nothing)

                ' Validate the price element and its content.
                validator.ValidateElement("price", "http://www.contoso.com/books", Nothing)
                validator.ValidateEndElement(Nothing, book.Price)

                ' Validate the content of the book element.
                validator.ValidateEndElement(Nothing)
            Next

            ' Validate the content of the bookstore element.
            validator.ValidateEndElement(Nothing)

            ' Close the XmlReader object.
            reader.Close()

        End Sub

        Shared schemaInfo As XmlSchemaInfo = New XmlSchemaInfo()
        Shared dateTimeGetterContent As Object

        Shared Function dateTimeGetterHandle() As Object

            Return dateTimeGetterContent

        End Function

        Shared Function dateTimeGetter(ByVal dateTime As DateTime) As XmlValueGetter

            dateTimeGetterContent = dateTime
            Return New XmlValueGetter(AddressOf dateTimeGetterHandle)

        End Function

        Shared Sub DisplaySchemaInfo()

            If Not schemaInfo.SchemaElement Is Nothing Then
                Console.WriteLine("Element '{0}' with type '{1}' is '{2}'", schemaInfo.SchemaElement.Name, schemaInfo.SchemaType, schemaInfo.Validity)
            ElseIf Not schemaInfo.SchemaAttribute Is Nothing Then
                Console.WriteLine("Attribute '{0}' with type '{1}' is '{2}'", schemaInfo.SchemaAttribute.Name, schemaInfo.SchemaType, schemaInfo.Validity)
            End If

        End Sub

        Shared Sub SchemaValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)

            Select Case e.Severity
                Case XmlSeverityType.Error
                    Console.WriteLine(vbCrLf & "Error: {0}", e.Message)
                    Exit Sub
                Case XmlSeverityType.Warning
                    Console.WriteLine(vbCrLf & "Warning: {0}", e.Message)
                    Exit Sub
            End Select

        End Sub

    End Class

    <XmlRootAttribute("bookstore", Namespace:="http://www.contoso.com/books", IsNullable:=False)> _
    Public Class ContosoBooks

        <XmlElementAttribute("book")> _
        Public book() As BookType

    End Class

    Public Class BookType

        <XmlAttributeAttribute("genre")> _
        Public Genre As String

        <XmlAttributeAttribute("publicationdate", DataType:="date")> _
        Public PublicationDate As DateTime

        <XmlAttributeAttribute("ISBN")> _
        Public Isbn As String

        <XmlElementAttribute("title")> _
        Public Title As String

        <XmlElementAttribute("author")> _
        Public Author As BookAuthor

        <XmlElementAttribute("price")> _
        Public Price As Decimal

    End Class

    Public Class BookAuthor

        <XmlElementAttribute("name")> _
        Public Name As String

        <XmlElementAttribute("first-name")> _
        Public FirstName As String

        <XmlElementAttribute("last-name")> _
        Public LastName As String

    End Class

End Namespace

The example takes the contosoBooks.xml file 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>

The example also takes the contosoBooks.xsd as an input.

<?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>

Validating XML Data using XmlSchemaValidator

To begin validating an XML infoset, you must first initialize a new instance of the XmlSchemaValidator class using the XmlSchemaValidator constructor.

The XmlSchemaValidator constructor takes XmlNameTable, XmlSchemaSet, and XmlNamespaceManager objects as parameters as well as a XmlSchemaValidationFlags value as a parameter. The XmlNameTable object is used to atomize well-known namespace strings like the schema namespace, the XML namespace, and so on, and is passed to the ParseValue method while validating simple content. The XmlSchemaSet object contains the XML schemas used to validate the XML infoset. The XmlNamespaceManager object is used to resolve namespaces encountered during validation. The XmlSchemaValidationFlags value is used to disable certain features of validation.

For more information about the XmlSchemaValidator constructor, see the XmlSchemaValidator class reference documentation.

Initializing Validation

After an XmlSchemaValidator object has been constructed, there are two overloaded Initialize methods used to initialize the state of the XmlSchemaValidator object. The following are the two Initialize methods.

The default XmlSchemaValidator.Initialize method initializes an XmlSchemaValidator object to its starting state, and the overloaded XmlSchemaValidator.Initialize method that takes an XmlSchemaObject as a parameter initializes an XmlSchemaValidator object to its starting state for partial validation.

Both Initialize methods can only be called immediately after an XmlSchemaValidator object has been constructed or after a call to EndValidation.

For an example of the XmlSchemaValidator.Initialize method, see the example in the introduction. For more information about the Initialize method, see the XmlSchemaValidator class reference documentation.

Partial Validation

The XmlSchemaValidator.Initialize method that takes an XmlSchemaObject as a parameter initializes an XmlSchemaValidator object to its starting state for partial validation.

In the following example, an XmlSchemaObject is initialized for partial validation using the XmlSchemaValidator.Initialize method. The orderNumber schema element is passed by selecting the schema element by XmlQualifiedName in the XmlSchemaObjectTable collection returned by the GlobalElements property of the XmlSchemaSet object. The XmlSchemaValidator object then validates this specific element.

Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
schemaSet.Add(Nothing, "schema.xsd")
schemaSet.Compile()
Dim nameTable As NameTable = New NameTable()
Dim manager As XmlNamespaceManager = New XmlNamespaceManager(nameTable)

Dim validator As XmlSchemaValidator = New XmlSchemaValidator(nameTable, schemaSet, manager, XmlSchemaValidationFlags.None)
validator.Initialize(schemaSet.GlobalElements.Item(New XmlQualifiedName("orderNumber")))

validator.ValidateElement("orderNumber", "", Nothing)
validator.ValidateEndOfAttributes(Nothing)
validator.ValidateText("123")
validator.ValidateEndElement(Nothing)
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "schema.xsd");
schemaSet.Compile();
NameTable nameTable = new NameTable();
XmlNamespaceManager manager = new XmlNamespaceManager(nameTable);

XmlSchemaValidator validator = new XmlSchemaValidator(nameTable, schemaSet, manager, XmlSchemaValidationFlags.None);
validator.Initialize(schemaSet.GlobalElements[new XmlQualifiedName("orderNumber")]);

validator.ValidateElement("orderNumber", "", null);
validator.ValidateEndOfAttributes(null);
validator.ValidateText("123");
validator.ValidateEndElement(null);

The example takes the following XML schema as input.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="orderNumber" type="xs:int" />
</xs:schema>

For more information about the Initialize method, see the XmlSchemaValidator class reference documentation.

Adding Additional Schemas

The AddSchema method of the XmlSchemaValidator class is used to add an XML schema to the set of schemas used during validation. The AddSchema method can be used to simulate the effect of encountering an inline XML schema in the XML infoset being validated.

Note

The target namespace of the XmlSchema parameter cannot match that of any element or attribute already encountered by the XmlSchemaValidator object.

If the XmlSchemaValidationFlags.ProcessInlineSchema value was not passed as a parameter to the XmlSchemaValidator constructor, the AddSchema method does nothing.

The result of the AddSchema method is dependant on the current XML node context being validated. For more information about validation contexts, see the "Validation Context" section of this topic.

For more information about the AddSchema method, see the XmlSchemaValidator class reference documentation.

Validating Elements, Attributes, and Content

The XmlSchemaValidator class provides several methods used to validate elements, attributes, and content in an XML infoset against XML schemas. The following table describes each of these methods.

Method Description
ValidateElement Validates the element name in the current context.
ValidateAttribute Validates the attribute in the current element context or against the XmlSchemaAttribute object passed as a parameter to the Initialize method.
ValidateEndOfAttributes Verifies whether all the required attributes in the element context are present and prepares the XmlSchemaValidator object to validate the child content of the element.
ValidateText Validates whether text is allowed in the current element context, and accumulates the text for validation if the current element has simple content.
ValidateWhitespace Validates whether white-space is allowed in the current element context, and accumulates the white-space for validation whether the current element has simple content.
ValidateEndElement Verifies whether the text content of the element is valid according to its data type for elements with simple content, and verifies whether the content of the current element is complete for elements with complex content.
SkipToEndElement Skips validation of the current element content and prepares the XmlSchemaValidator object to validate content in the parent element's context.
EndValidation Ends validation and checks identity constraints for the entire XML document if the ProcessIdentityConstraints validation option is set.

Note

The XmlSchemaValidator class has a defined state transition that enforces the sequence and occurrence of calls made to each of the methods described in the previous table. The specific state transition of the XmlSchemaValidator class is described in the "XmlSchemaValidator State Transition" section of this topic.

For an example of the methods used to validate elements, attributes, and content in an XML infoset, see the example in the previous section. For more information about these methods, see the XmlSchemaValidator class reference documentation.

Validating Content Using an XmlValueGetter

The XmlValueGetterdelegate can be used to pass the value of attribute, text, or white-space nodes as a Common Language Runtime (CLR) types compatible with the XML Schema Definition Language (XSD) type of the attribute, text, or white-space node. An XmlValueGetterdelegate is useful if the CLR value of an attribute, text, or white-space node is already available, and avoids the cost of converting it to a string and then reparsing it again for validation.

The ValidateAttribute, ValidateText, and ValidateWhitespace methods are overloaded and accept the value of attribute, text, or white-space nodes as a string or XmlValueGetterdelegate.

The following methods of the XmlSchemaValidator class accept an XmlValueGetterdelegate as a parameter.

The following is an example XmlValueGetterdelegate taken from the XmlSchemaValidator class example in the introduction. The XmlValueGetterdelegate returns the value of an attribute as a DateTime object. To validate this DateTime object returned by the XmlValueGetter, the XmlSchemaValidator object first converts it to the ValueType (ValueType is the default CLR mapping for the XSD type) for the data type of the attribute and then checks facets on the converted value.

Shared dateTimeGetterContent As Object

Shared Function DateTimeGetterHandle() As Object
    Return dateTimeGetterContent
End Function

Shared Function DateTimeGetter(dateTime As DateTime) As XmlValueGetter
    dateTimeGetterContent = dateTime
    Return New XmlValueGetter(AddressOf DateTimeGetterHandle)
End Function
static object dateTimeGetterContent;

static object DateTimeGetterHandle()
{
    return dateTimeGetterContent;
}

static XmlValueGetter DateTimeGetter(DateTime dateTime)
{
    dateTimeGetterContent = dateTime;
    return new XmlValueGetter(dateTimeGetterHandle);
}

For a complete example of the XmlValueGetterdelegate, see the example in the introduction. For more information about the XmlValueGetterdelegate, see the XmlValueGetter, and XmlSchemaValidator class reference documentation.

Post-Schema-Validation-Information

The XmlSchemaInfo class represents some of the Post-Schema-Validation-Information of an XML node validated by the XmlSchemaValidator class. Various methods of the XmlSchemaValidator class accept an XmlSchemaInfo object as an optional, (null) out parameter.

Upon successful validation, properties of the XmlSchemaInfo object are set with the results of the validation. For example, upon successful validation of an attribute using the ValidateAttribute method, the XmlSchemaInfo object's (if specified) SchemaAttribute, SchemaType, MemberType, and Validity properties are set with the results of the validation.

The following XmlSchemaValidator class methods accept an XmlSchemaInfo object as an out parameter.

For a complete example of the XmlSchemaInfo class, see the example in the introduction. For more information about the XmlSchemaInfo class, see the XmlSchemaInfo class reference documentation.

Retrieving Expected Particles, Attributes, and Unspecified Default Attributes

The XmlSchemaValidator class provides the GetExpectedAttributes, GetExpectedParticles, and GetUnspecifiedDefaultAttributes methods to retrieve the expected particles, attributes, and unspecified default attributes in the current validation context.

Retrieving Expected Particles

The GetExpectedParticles method returns an array of XmlSchemaParticle objects containing the expected particles in the current element context. The valid particles that can be returned by the GetExpectedParticles method are instances of the XmlSchemaElement and XmlSchemaAny classes.

When the compositor for the content model is an xs:sequence, only the next particle in the sequence is returned. If the compositor for the content model is an xs:all or an xs:choice, then all valid particles that could follow in the current element context are returned.

Note

If the GetExpectedParticles method is called immediately after calling the Initialize method, the GetExpectedParticles method returns all global elements.

For example, in the XML Schema Definition Language (XSD) schema and XML document that follow, after validating the book element, the book element is the current element context. The GetExpectedParticles method returns an array containing a single XmlSchemaElement object representing the title element. When the validation context is the title element, the GetExpectedParticles method returns an empty array. If the GetExpectedParticles method is called after the title element has been validated but before the description element has been validated, it returns an array containing a single XmlSchemaElement object representing the description element. If the GetExpectedParticles method is called after the description element has been validated then it returns an array containing a single XmlSchemaAny object representing the wildcard.

Dim reader As XmlReader =  XmlReader.Create("input.xml")

Dim schemaSet As New XmlSchemaSet()
schemaSet.Add(Nothing, "schema.xsd")
Dim manager As New XmlNamespaceManager(reader.NameTable)

Dim validator As New XmlSchemaValidator(reader.NameTable,schemaSet,manager,XmlSchemaValidationFlags.None)
validator.Initialize()

validator.ValidateElement("book", "", Nothing)

validator.ValidateEndOfAttributes(Nothing)
For Each element As XmlSchemaElement In validator.GetExpectedParticles()
    Console.WriteLine(element.Name)
Next

validator.ValidateElement("title", "", Nothing)
validator.ValidateEndOfAttributes(Nothing)
For Each element As XmlSchemaElement In validator.GetExpectedParticles()
    Console.WriteLine(element.Name)
Next
validator.ValidateEndElement(Nothing)

For Each element As XmlSchemaElement In validator.GetExpectedParticles()
    Console.WriteLine(element.Name)
Next

validator.ValidateElement("description", "", Nothing)
validator.ValidateEndOfAttributes(Nothing)
validator.ValidateEndElement(Nothing)

For Each particle As XmlSchemaParticle In validator.GetExpectedParticles()
    Console.WriteLine(particle.GetType())
Next

validator.ValidateElement("namespace", "", Nothing)
validator.ValidateEndOfAttributes(Nothing)
validator.ValidateEndElement(Nothing)

validator.ValidateEndElement(Nothing)
XmlReader reader = XmlReader.Create("input.xml");

var schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "schema.xsd");
var manager = new XmlNamespaceManager(reader.NameTable);

var validator = new XmlSchemaValidator(reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None);
validator.Initialize();

validator.ValidateElement("book", "", null);

validator.ValidateEndOfAttributes(null);
foreach (XmlSchemaElement element in validator.GetExpectedParticles())
{
    Console.WriteLine(element.Name);
}

validator.ValidateElement("title", "", null);
validator.ValidateEndOfAttributes(null);
foreach (XmlSchemaElement element in validator.GetExpectedParticles())
{
    Console.WriteLine(element.Name);
}
validator.ValidateEndElement(null);

foreach (XmlSchemaElement element in validator.GetExpectedParticles())
{
    Console.WriteLine(element.Name);
}

validator.ValidateElement("description", "", null);
validator.ValidateEndOfAttributes(null);
validator.ValidateEndElement(null);

foreach (XmlSchemaParticle particle in validator.GetExpectedParticles())
{
    Console.WriteLine(particle.GetType());
}

validator.ValidateElement("namespace", "", null);
validator.ValidateEndOfAttributes(null);
validator.ValidateEndElement(null);

validator.ValidateEndElement(null);

The example takes the following XML as input:

<xs:schema xmlns:xs="http://www.w3c.org/2001/XMLSchema">
  <xs:element name="book">
    <xs:sequence>
      <xs:element name="title" type="xs:string" />
      <xs:element name="description" type="xs:string" />
      <xs:any processContent="lax" maxOccurs="unbounded" />
    </xs:sequence>
  </xs:element>
</xs:schema>

The example takes the following XSD schema as input:

<book>
  <title>My Book</title>
  <description>My Book's Description</description>
  <namespace>System.Xml.Schema</namespace>
</book>

Note

The results of the GetExpectedParticles, GetExpectedAttributes, and AddSchema methods of the XmlSchemaValidator class are dependent on the current context being validated. For more information, see the "Validation Context" section of this topic.

For an example of the GetExpectedParticles method, see the example in the introduction. For more information about the GetExpectedParticles method, see the XmlSchemaValidator class reference documentation.

Retrieving Expected Attributes

The GetExpectedAttributes method returns an array of XmlSchemaAttribute objects containing the expected attributes in the current element context.

For example, in the example in the introduction, the GetExpectedAttributes method is used to retrieve all the attributes of the book element.

If you call the GetExpectedAttributes method immediately after the ValidateElement method, all the attributes that could appear in the XML document are returned. However, if you call the GetExpectedAttributes method after one or more calls to the ValidateAttribute method, the attributes that have not yet been validated for the current element are returned.

Note

The results of the GetExpectedParticles, GetExpectedAttributes, and AddSchema methods of the XmlSchemaValidator class are dependent on the current context being validated. For more information, see the "Validation Context" section of this topic.

For an example of the GetExpectedAttributes method, see the example in the introduction. For more information about the GetExpectedAttributes method, see the XmlSchemaValidator class reference documentation.

Retrieving Unspecified Default Attributes

The GetUnspecifiedDefaultAttributes method populates the ArrayList specified with XmlSchemaAttribute objects for any attributes with default values that have not been previously validated using the ValidateAttribute method in the element context. The GetUnspecifiedDefaultAttributes method should be called after calling the ValidateAttribute method on each attribute in the element context. The GetUnspecifiedDefaultAttributes method should be used to determine what default attributes are to be inserted into the XML document being validated.

For more information about the GetUnspecifiedDefaultAttributes method, see the XmlSchemaValidator class reference documentation.

Handling Schema Validation Events

Schema validation warnings and errors encountered during validation are handled by the ValidationEventHandler event of the XmlSchemaValidator class.

Schema validation warnings have an XmlSeverityType value of Warning and schema validation errors have an XmlSeverityType value of Error. If no ValidationEventHandler has been assigned, an XmlSchemaValidationException is thrown for all schema validation errors with an XmlSeverityType value of Error. However, an XmlSchemaValidationException is not thrown for schema validation warnings with an XmlSeverityType value of Warning.

The following is an example of a ValidationEventHandler that receives schema validation warnings and errors encountered during schema validation taken from the example in the introduction.

Shared Sub SchemaValidationEventHandler(sender As Object, e As ValidationEventArgs)

    Select Case e.Severity
        Case XmlSeverityType.Error
            Console.WriteLine(vbCrLf & "Error: {0}", e.Message)
            Exit Sub
        Case XmlSeverityType.Warning
            Console.WriteLine(vbCrLf & "Warning: {0}", e.Message)
            Exit Sub
    End Select
End Sub
static void SchemaValidationEventHandler(object sender, ValidationEventArgs e)
{
    switch (e.Severity)
    {
        case XmlSeverityType.Error:
            Console.WriteLine("\nError: {0}", e.Message);
            break;
        case XmlSeverityType.Warning:
            Console.WriteLine("\nWarning: {0}", e.Message);
            break;
    }
}

For a complete example of the ValidationEventHandler, see the example in the introduction. For more information, see the XmlSchemaInfo class reference documentation.

XmlSchemaValidator State Transition

The XmlSchemaValidator class has a defined state transition that enforces the sequence and occurrence of calls made to each of the methods used to validate elements, attributes, and content in an XML infoset.

The following table describes the state transition of the XmlSchemaValidator class, and the sequence and occurrence of method calls that can be made in each state.

State Transition
Validate Initialize (ValidateAttribute | TopLevel*) EndValidation
TopLevel ValidateWhitespace | ValidateText | Element
Element ValidateElement ValidateAttribute* (ValidateEndOfAttributes Content*)? ValidateEndElement |

ValidateElement ValidateAttribute* SkipToEndElement |

ValidateElement ValidateAttribute* ValidateEndOfAttributes Content* SkipToEndElement |
Content ValidateWhitespace | ValidateText | Element

Note

An InvalidOperationException is thrown by each of the methods in the table above when the call to the method is made in the incorrect sequence according to the current state of an XmlSchemaValidator object.

The state transition table above uses punctuation symbols to describe the methods and other states that can be called for each state of the state transition of the XmlSchemaValidator class. The symbols used are the same symbols found in the XML Standards reference for Document Type Definition (DTD).

The following table describes how the punctuation symbols found in the state transition table above affect the methods and other states that can be called for each state in the state transition of the XmlSchemaValidator class.

Symbol Description
| Either method or state (the one before the bar or the one after it) can be called.
? The method or state that precedes the question mark is optional but if it is called it can only be called once.
* The method or state that precedes the * symbol is optional, and can be called more than once.

Validation Context

The methods of the XmlSchemaValidator class used to validate elements, attributes, and content in an XML infoset, change the validation context of an XmlSchemaValidator object. For example, the SkipToEndElement method skips validation of the current element content and prepares the XmlSchemaValidator object to validate content in the parent element's context; it is equivalent to skipping validation for all the children of the current element and then calling the ValidateEndElement method.

The results of the GetExpectedParticles, GetExpectedAttributes, and AddSchema methods of the XmlSchemaValidator class are dependent on the current context being validated.

The following table describes the results of calling these methods after calling one of the methods of the XmlSchemaValidator class used to validate elements, attributes, and content in an XML infoset.

Method GetExpectedParticles GetExpectedAttributes AddSchema
Initialize If the default Initialize method is called, GetExpectedParticles returns an array containing all global elements.

If the overloaded Initialize method that takes an XmlSchemaObject as a parameter is called to initialize partial validation of an element, GetExpectedParticles returns only the element to which the XmlSchemaValidator object was initialized.
If the default Initialize method is called, GetExpectedAttributes returns an empty array.

If the overload of the Initialize method that takes an XmlSchemaObject as a parameter is called to initialize partial validation of an attribute, GetExpectedAttributes returns only the attribute to which the XmlSchemaValidator object was initialized.
Adds the schema to the XmlSchemaSet of the XmlSchemaValidator object if it has no preprocessing errors.
ValidateElement If the context element is valid, GetExpectedParticles returns the sequence of elements expected as children of the context element.

If the context element is invalid, GetExpectedParticles returns an empty array.
If the context element is valid, and if no call to ValidateAttribute has been previously made, GetExpectedAttributes returns a list of all the attributes defined on the context element.

If some attributes have already been validated, GetExpectedAttributes returns a list of the remaining attributes to be validated.

If the context element is invalid, GetExpectedAttributes returns an empty array.
Same as above.
ValidateAttribute If the context attribute is a top-level attribute, GetExpectedParticles returns an empty array.

Otherwise GetExpectedParticles returns the sequence of elements expected as the first child of the context element.
If the context attribute is a top-level attribute, GetExpectedAttributes returns an empty array.

Otherwise GetExpectedAttributes returns the list of remaining attributes to be validated.
Same as above.
GetUnspecifiedDefaultAttributes GetExpectedParticles returns the sequence of elements expected as the first child of the context element. GetExpectedAttributes returns a list of the required and optional attributes that are yet to be validated for the context element. Same as above.
ValidateEndOfAttributes GetExpectedParticles returns the sequence of elements expected as the first child of the context element. GetExpectedAttributes returns an empty array. Same as above.
ValidateText If the context element's contentType is Mixed, GetExpectedParticles returns the sequence of elements expected in the next position.

If the context element's contentType is TextOnly or Empty, GetExpectedParticles returns an empty array.

If the context element's contentType is ElementOnly, GetExpectedParticles returns the sequence of elements expected in the next position but a validation error has already occurred.
GetExpectedAttributes returns the context element's list of attributes not validated. Same as above.
ValidateWhitespace If the context white-space is top-level white-space, GetExpectedParticles returns an empty array.

Otherwise the GetExpectedParticles method's behavior is the same as in ValidateText.
If the context white-space is top-level white-space, GetExpectedAttributes returns an empty array.

Otherwise the GetExpectedAttributes method's behavior is the same as in ValidateText.
Same as above.
ValidateEndElement GetExpectedParticles returns the sequence of elements expected after the context element (possible siblings). GetExpectedAttributes returns the context element's list of attributes not validated.

If the context element has no parent then GetExpectedAttributes returns an empty list (the context element is the parent of the current element on which ValidateEndElement was called).
Same as above.
SkipToEndElement Same as ValidateEndElement. Same as ValidateEndElement. Same as above.
EndValidation Returns an empty array. Returns an empty array. Same as above.

Note

The values returned by the various properties of the XmlSchemaValidator class are not altered by calling any of the methods in the above table.

See also