Skip to content

Latest commit

 

History

History
481 lines (343 loc) · 40 KB

xmlschemavalidator-push-based-validation.md

File metadata and controls

481 lines (343 loc) · 40 KB
description title ms.date dev_langs ms.assetid
Learn more about: XmlSchemaValidator Push-Based Validation
XmlSchemaValidator Push-Based Validation
03/30/2017
csharp
vb
911d4460-dd91-4958-85b2-2ca3299f9ec6

XmlSchemaValidator Push-Based Validation

The xref:System.Xml.Schema.XmlSchemaValidator class provides an efficient, high-performance mechanism to validate XML data against XML schemas in a push-based manner. For example, the xref:System.Xml.Schema.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 xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator class to validate the contosoBooks.xml file against the contosoBooks.xsd schema. The example uses the xref:System.Xml.Serialization.XmlSerializer class to deserialize the contosoBooks.xml file and pass the value of the nodes to the methods of the xref:System.Xml.Schema.XmlSchemaValidator class.

Note

This example is used throughout the sections of this topic.

[!code-csharpXmlSchemaValidatorExamples#1] [!code-vbXmlSchemaValidatorExamples#1]

The example takes the contosoBooks.xml file as input.

[!code-xmlXPathXMLExamples#2]

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 xref:System.Xml.Schema.XmlSchemaValidator class using the xref:System.Xml.Schema.XmlSchemaValidator.%23ctor%2A constructor.

The xref:System.Xml.Schema.XmlSchemaValidator.%23ctor%2A constructor takes xref:System.Xml.XmlNameTable, xref:System.Xml.Schema.XmlSchemaSet, and xref:System.Xml.XmlNamespaceManager objects as parameters as well as a xref:System.Xml.Schema.XmlSchemaValidationFlags value as a parameter. The xref:System.Xml.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 xref:System.Xml.Schema.XmlSchemaDatatype.ParseValue%2A method while validating simple content. The xref:System.Xml.Schema.XmlSchemaSet object contains the XML schemas used to validate the XML infoset. The xref:System.Xml.XmlNamespaceManager object is used to resolve namespaces encountered during validation. The xref:System.Xml.Schema.XmlSchemaValidationFlags value is used to disable certain features of validation.

For more information about the xref:System.Xml.Schema.XmlSchemaValidator.%23ctor%2A constructor, see the xref:System.Xml.Schema.XmlSchemaValidator class reference documentation.

Initializing Validation

After an xref:System.Xml.Schema.XmlSchemaValidator object has been constructed, there are two overloaded xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A methods used to initialize the state of the xref:System.Xml.Schema.XmlSchemaValidator object. The following are the two xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A methods.

  • xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A?displayProperty=nameWithType

  • xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A?displayProperty=nameWithType

The default xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A?displayProperty=nameWithType method initializes an xref:System.Xml.Schema.XmlSchemaValidator object to its starting state, and the overloaded xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A?displayProperty=nameWithType method that takes an xref:System.Xml.Schema.XmlSchemaObject as a parameter initializes an xref:System.Xml.Schema.XmlSchemaValidator object to its starting state for partial validation.

Both xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A methods can only be called immediately after an xref:System.Xml.Schema.XmlSchemaValidator object has been constructed or after a call to xref:System.Xml.Schema.XmlSchemaValidator.EndValidation%2A.

For an example of the xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A?displayProperty=nameWithType method, see the example in the introduction. For more information about the xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A method, see the xref:System.Xml.Schema.XmlSchemaValidator class reference documentation.

Partial Validation

The xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A?displayProperty=nameWithType method that takes an xref:System.Xml.Schema.XmlSchemaObject as a parameter initializes an xref:System.Xml.Schema.XmlSchemaValidator object to its starting state for partial validation.

In the following example, an xref:System.Xml.Schema.XmlSchemaObject is initialized for partial validation using the xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A?displayProperty=nameWithType method. The orderNumber schema element is passed by selecting the schema element by xref:System.Xml.XmlQualifiedName in the xref:System.Xml.Schema.XmlSchemaObjectTable collection returned by the xref:System.Xml.Schema.XmlSchemaSet.GlobalElements%2A property of the xref:System.Xml.Schema.XmlSchemaSet object. The xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A method, see the xref:System.Xml.Schema.XmlSchemaValidator class reference documentation.

Adding Additional Schemas

The xref:System.Xml.Schema.XmlSchemaValidator.AddSchema%2A method of the xref:System.Xml.Schema.XmlSchemaValidator class is used to add an XML schema to the set of schemas used during validation. The xref:System.Xml.Schema.XmlSchemaValidator.AddSchema%2A 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 xref:System.Xml.Schema.XmlSchema parameter cannot match that of any element or attribute already encountered by the xref:System.Xml.Schema.XmlSchemaValidator object.

If the xref:System.Xml.Schema.XmlSchemaValidationFlags.ProcessInlineSchema?displayProperty=nameWithType value was not passed as a parameter to the xref:System.Xml.Schema.XmlSchemaValidator.%23ctor%2A constructor, the xref:System.Xml.Schema.XmlSchemaValidator.AddSchema%2A method does nothing.

The result of the xref:System.Xml.Schema.XmlSchemaValidator.AddSchema%2A 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 xref:System.Xml.Schema.XmlSchemaValidator.AddSchema%2A method, see the xref:System.Xml.Schema.XmlSchemaValidator class reference documentation.

Validating Elements, Attributes, and Content

The xref:System.Xml.Schema.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
xref:System.Xml.Schema.XmlSchemaValidator.ValidateElement%2A Validates the element name in the current context.
xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A Validates the attribute in the current element context or against the xref:System.Xml.Schema.XmlSchemaAttribute object passed as a parameter to the xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A method.
xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndOfAttributes%2A Verifies whether all the required attributes in the element context are present and prepares the xref:System.Xml.Schema.XmlSchemaValidator object to validate the child content of the element.
xref:System.Xml.Schema.XmlSchemaValidator.ValidateText%2A Validates whether text is allowed in the current element context, and accumulates the text for validation if the current element has simple content.
xref:System.Xml.Schema.XmlSchemaValidator.ValidateWhitespace%2A 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.
xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndElement%2A 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.
xref:System.Xml.Schema.XmlSchemaValidator.SkipToEndElement%2A Skips validation of the current element content and prepares the xref:System.Xml.Schema.XmlSchemaValidator object to validate content in the parent element's context.
xref:System.Xml.Schema.XmlSchemaValidator.EndValidation%2A Ends validation and checks identity constraints for the entire XML document if the xref:System.Xml.Schema.XmlSchemaValidationFlags.ProcessIdentityConstraints validation option is set.

Note

The xref:System.Xml.Schema.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 xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator class reference documentation.

Validating Content Using an XmlValueGetter

The xref:System.Xml.Schema.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 xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A, xref:System.Xml.Schema.XmlSchemaValidator.ValidateText%2A, and xref:System.Xml.Schema.XmlSchemaValidator.ValidateWhitespace%2A methods are overloaded and accept the value of attribute, text, or white-space nodes as a string or xref:System.Xml.Schema.XmlValueGetterdelegate.

The following methods of the xref:System.Xml.Schema.XmlSchemaValidator class accept an xref:System.Xml.Schema.XmlValueGetterdelegate as a parameter.

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateText%2A

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateWhitespace%2A

The following is an example xref:System.Xml.Schema.XmlValueGetterdelegate taken from the xref:System.Xml.Schema.XmlSchemaValidator class example in the introduction. The xref:System.Xml.Schema.XmlValueGetterdelegate returns the value of an attribute as a xref:System.DateTime object. To validate this xref:System.DateTime object returned by the xref:System.Xml.Schema.XmlValueGetter, the xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlValueGetterdelegate, see the example in the introduction. For more information about the xref:System.Xml.Schema.XmlValueGetterdelegate, see the xref:System.Xml.Schema.XmlValueGetter, and xref:System.Xml.Schema.XmlSchemaValidator class reference documentation.

Post-Schema-Validation-Information

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

Upon successful validation, properties of the xref:System.Xml.Schema.XmlSchemaInfo object are set with the results of the validation. For example, upon successful validation of an attribute using the xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A method, the xref:System.Xml.Schema.XmlSchemaInfo object's (if specified) xref:System.Xml.Schema.XmlSchemaInfo.SchemaAttribute%2A, xref:System.Xml.Schema.XmlSchemaInfo.SchemaType%2A, xref:System.Xml.Schema.XmlSchemaInfo.MemberType%2A, and xref:System.Xml.Schema.XmlSchemaInfo.Validity%2A properties are set with the results of the validation.

The following xref:System.Xml.Schema.XmlSchemaValidator class methods accept an xref:System.Xml.Schema.XmlSchemaInfo object as an out parameter.

  • xref:System.Xml.Schema.XmlSchemaValidator.SkipToEndElement%2A

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateElement%2A

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateElement%2A

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndElement%2A

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndElement%2A

  • xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndOfAttributes%2A

For a complete example of the xref:System.Xml.Schema.XmlSchemaInfo class, see the example in the introduction. For more information about the xref:System.Xml.Schema.XmlSchemaInfo class, see the xref:System.Xml.Schema.XmlSchemaInfo class reference documentation.

Retrieving Expected Particles, Attributes, and Unspecified Default Attributes

The xref:System.Xml.Schema.XmlSchemaValidator class provides the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A, and xref:System.Xml.Schema.XmlSchemaValidator.GetUnspecifiedDefaultAttributes%2A methods to retrieve the expected particles, attributes, and unspecified default attributes in the current validation context.

Retrieving Expected Particles

The xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A method returns an array of xref:System.Xml.Schema.XmlSchemaParticle objects containing the expected particles in the current element context. The valid particles that can be returned by the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A method are instances of the xref:System.Xml.Schema.XmlSchemaElement and xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A method is called immediately after calling the xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A method, the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A 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 xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A method returns an array containing a single xref:System.Xml.Schema.XmlSchemaElement object representing the title element. When the validation context is the title element, the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A method returns an empty array. If the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A 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 xref:System.Xml.Schema.XmlSchemaElement object representing the description element. If the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A method is called after the description element has been validated then it returns an array containing a single xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A, and xref:System.Xml.Schema.XmlSchemaValidator.AddSchema%2A methods of the xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A method, see the example in the introduction. For more information about the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A method, see the xref:System.Xml.Schema.XmlSchemaValidator class reference documentation.

Retrieving Expected Attributes

The xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A method returns an array of xref:System.Xml.Schema.XmlSchemaAttribute objects containing the expected attributes in the current element context.

For example, in the example in the introduction, the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A method is used to retrieve all the attributes of the book element.

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

Note

The results of the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A, and xref:System.Xml.Schema.XmlSchemaValidator.AddSchema%2A methods of the xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A method, see the example in the introduction. For more information about the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A method, see the xref:System.Xml.Schema.XmlSchemaValidator class reference documentation.

Retrieving Unspecified Default Attributes

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

For more information about the xref:System.Xml.Schema.XmlSchemaValidator.GetUnspecifiedDefaultAttributes%2A method, see the xref:System.Xml.Schema.XmlSchemaValidator class reference documentation.

Handling Schema Validation Events

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

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

The following is an example of a xref:System.Xml.Schema.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 xref:System.Xml.Schema.ValidationEventHandler, see the example in the introduction. For more information, see the xref:System.Xml.Schema.XmlSchemaInfo class reference documentation.

XmlSchemaValidator State Transition

The xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator class, and the sequence and occurrence of method calls that can be made in each state.

State Transition
Validate xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A (xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A | TopLevel*) xref:System.Xml.Schema.XmlSchemaValidator.EndValidation%2A
TopLevel xref:System.Xml.Schema.XmlSchemaValidator.ValidateWhitespace%2A | xref:System.Xml.Schema.XmlSchemaValidator.ValidateText%2A | Element
Element xref:System.Xml.Schema.XmlSchemaValidator.ValidateElement%2A xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A* (xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndOfAttributes%2A Content*)? xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndElement%2A |

xref:System.Xml.Schema.XmlSchemaValidator.ValidateElement%2A xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A* xref:System.Xml.Schema.XmlSchemaValidator.SkipToEndElement%2A |

xref:System.Xml.Schema.XmlSchemaValidator.ValidateElement%2A xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A* xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndOfAttributes%2A Content* xref:System.Xml.Schema.XmlSchemaValidator.SkipToEndElement%2A |
Content xref:System.Xml.Schema.XmlSchemaValidator.ValidateWhitespace%2A | xref:System.Xml.Schema.XmlSchemaValidator.ValidateText%2A | Element

Note

An xref:System.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 xref:System.Xml.Schema.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 xref:System.Xml.Schema.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 xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator class used to validate elements, attributes, and content in an XML infoset, change the validation context of an xref:System.Xml.Schema.XmlSchemaValidator object. For example, the xref:System.Xml.Schema.XmlSchemaValidator.SkipToEndElement%2A method skips validation of the current element content and prepares the xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndElement%2A method.

The results of the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A, and xref:System.Xml.Schema.XmlSchemaValidator.AddSchema%2A methods of the xref:System.Xml.Schema.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 xref:System.Xml.Schema.XmlSchemaValidator class used to validate elements, attributes, and content in an XML infoset.

Method GetExpectedParticles GetExpectedAttributes AddSchema
xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A If the default xref:System.Xml.Schema.XmlSchemaValidator.Initialize%2A method is called, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A returns an array containing all global elements.

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

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

If the context element is invalid, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A returns an empty array.
If the context element is valid, and if no call to xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A has been previously made, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A returns a list of all the attributes defined on the context element.

If some attributes have already been validated, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A returns a list of the remaining attributes to be validated.

If the context element is invalid, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A returns an empty array.
Same as above.
xref:System.Xml.Schema.XmlSchemaValidator.ValidateAttribute%2A If the context attribute is a top-level attribute, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A returns an empty array.

Otherwise xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A returns the sequence of elements expected as the first child of the context element.
If the context attribute is a top-level attribute, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A returns an empty array.

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

If the context element's contentType is TextOnly or Empty, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A returns an empty array.

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

Otherwise the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A method's behavior is the same as in xref:System.Xml.Schema.XmlSchemaValidator.ValidateText%2A.
If the context white-space is top-level white-space, xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A returns an empty array.

Otherwise the xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A method's behavior is the same as in xref:System.Xml.Schema.XmlSchemaValidator.ValidateText%2A.
Same as above.
xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndElement%2A xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedParticles%2A returns the sequence of elements expected after the context element (possible siblings). xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A returns the context element's list of attributes not validated.

If the context element has no parent then xref:System.Xml.Schema.XmlSchemaValidator.GetExpectedAttributes%2A returns an empty list (the context element is the parent of the current element on which xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndElement%2A was called).
Same as above.
xref:System.Xml.Schema.XmlSchemaValidator.SkipToEndElement%2A Same as xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndElement%2A. Same as xref:System.Xml.Schema.XmlSchemaValidator.ValidateEndElement%2A. Same as above.
xref:System.Xml.Schema.XmlSchemaValidator.EndValidation%2A Returns an empty array. Returns an empty array. Same as above.

Note

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

See also

  • xref:System.Xml.Schema.XmlSchemaValidator