Validation and the Schema Object Model

There are two exception events that can occur during schema validation: warnings and errors. A warning occurs when the parser encounters an element that it does not understand and therefore cannot validate. The parser can continue to process the instance document after a warning has occurred. An error, on the other hand, occurs when the parser cannot complete its task because it has encountered an invalid situation.

Warnings

A warning typically occurs when the parser encounters elements for which it cannot find schema information to validate against.

In the following example, the XmlValidatingReader issues warnings about elements that it does not understand such as html, p, br, b, and i elements. XmlValidatingReader does not generate errors when it encounters these elements because the any element indicates that the subject element can have an unlimited amount of markup from any namespace within the XML document.

The following XML Schema outlines the contents of Warning.xsd.

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <xs:element name="content" type="contentType" />
   <xs:complexType name="contentType">
    <xs:sequence>
      <xs:element name="subject" type="subjectType" />
    </xs:sequence>
   </xs:complexType>
   <xs:complexType name="subjectType" >
    <xs:sequence>
     <xs:any namespace="##any" processContents="skip" maxOccurs="unbounded"/>
    </xs:sequence>
   <xs:anyAttribute namespace="##any" processContents="skip" />
 </xs:complexType>
</xs:schema>

The following outlines the contents of Warning.xml that compiles to Warning.xsd.

<?xml version="1.0" ?>
<content xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
    xsi:noNamespaceSchemaLocation="Warning.xsd">
 <subject>
   <html>
   <p>sdfsdf</p>
   <br/>
   <b> bold or <i> italic </i> or strong </b>
   </html>
 </subject>
</content>

Errors

An error is an event that prevents the parser from continuing to process the XML document that is being validated. An error can occur if an element is positioned incorrectly in the content model of its parent element.

The following example generates an error because the extension element is not a valid child element for the complexType element.

<xs:complexType>
 <xs:extension base='xs:decimal'>
   <xs:attribute name='sizing' type='xs:string' />
  </xs:extension>
</xs:complexType" />

Handling Validation Events

To handle errors and warnings, the Schema Object Model (SOM) supports the use of a ValidationEventHandler delegate, which is a callback that you design. This callback is called when an error or warning occurs during validation.

If a ValidationEventHandler is registered, it is possible for the parser to recover from errors by discarding the invalid information and passing the information about the error to the ValidationEventHandler. If no ValidationEventHandler is specified, rather than recovering from errors the processing stops.

When a validation event occurs, the ValidationEventHandler passes a ValidationEventArgs object with a Severity property that you can use to determine the severity of a validation event. The ValidationEventArgs also has a Message property containing the error message, as well as an Exception property containing the exception that would have been thrown if no ValidationEventHandler was specified.

The following table shows the relationship between errors and warnings and the ValidationEventHandler.

    ValidationEventHandler No ValidationEventHandler
Warning If the ValidationEventHandler is called and is passed a ValidationEventArgs.Severity that is equal to XmlSeverityType.Warning, processing of the document continues. No exception is thrown and processing of the schema document continues.
Error If the ValidationEventHandler is called and is passed a ValidationEventArgs.Severity that is equal to XmlSeverityType.Error, processing of the document continues and invalid data is discarded. An exception is thrown and processing of the schema document stops.

The following example uses a ValidationEventHandler to handle the validation errors in the XML Schema file. Note that even though there are validation errors in the file, the entire file is validated instead of an exception being thrown at the first occurrence of an error.

Imports System.IO
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.Text

Class ReadWriteSample
 
Public Shared Sub ValidationCallbackOne(sender As Object, args As ValidationEventArgs)
      
      If args.Severity = XmlSeverityType.Warning Then
         Console.Write("WARNING: ")
      Else
         If args.Severity = XmlSeverityType.Error Then
            Console.Write("ERROR: ")
         End If 
      End If
      Console.WriteLine(args.Message) ' Prints the error to the screen.
   End Sub 'ValidationCallbackOne
   
   Public Shared Sub Main()
      
      Try
         
         Dim reader As New XmlTextReader("Bad_example.xsd")
         Dim myschema As XmlSchema = XmlSchema.Read(reader, New ValidationEventHandler(AddressOf ValidationCallbackOne))
         
         myschema.Write(Console.Out)
         Dim file As New FileStream("New.xsd", FileMode.Create, FileAccess.ReadWrite)
         Dim xwriter As New XmlTextWriter(file, New UTF8Encoding())
         xwriter.Formatting = Formatting.Indented
         myschema.Write(xwriter)
      
      Catch e As Exception
         Console.WriteLine(e)
      End Try
   End Sub 'Main 
End Class 'ReadWriteSample
[C#]
using System.IO; 
using System;
using System.Xml;  
using System.Xml.Schema;
using System.Text; 

class ReadWriteSample {
   
public static void ValidationCallbackOne(object sender, ValidationEventArgs args) {

if(args.Severity == XmlSeverityType.Warning)
 Console.Write("WARNING: ");
  else if(args.Severity == XmlSeverityType.Error)
 Console.Write("ERROR: ");

Console.WriteLine(args.Message); // Print the error to the screen.
}

public static void Main() {

   try{ 

   XmlTextReader reader = new XmlTextReader ("Bad_example.xsd");
   XmlSchema myschema = XmlSchema.Read(reader, new        ValidationEventHandler(ValidationCallbackOne)); 

   myschema.Write(Console.Out);
   FileStream file = new FileStream ("New.xsd", FileMode.Create,     FileAccess.ReadWrite);
   XmlTextWriter xwriter = new XmlTextWriter (file, new UTF8Encoding());
   xwriter.Formatting = Formatting.Indented;
   myschema.Write (xwriter);

    }catch(Exception e){
       Console.WriteLine(e);
    }
  }/* Main() */ 
}//ReadWriteSample 

The following XML Schema outlines the contents of the input file, Bad_example.xsd.

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="Play" 
                     targetNamespace="http://tempuri.org/Play.xsd" 
                     elementFormDefault="qualified" 
                     xmlns="http://tempuri.org/Play.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name='myShoeSize'>
 <xs:complexType>
  <xs:extension base='xs:decimal'>
    <xs:attribute name='sizing' type='xs:string' />
    <xs:extension />
   </xs:extension>
 </xs:complexType>
</xs:element>
<player></player>
</xs:schema>

See Also

XML Schema Object Model (SOM) | Validation of XML with Schemas