XML Schema Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.00

XSD Schema XML SAX Validator with Error Handler

This section describes a tutorial example on how to create an error handler to be used by the validator to alter the default error handling behavior.

As you can see from the previous section, the default error handling behavior is to stop the validation process immediately after the first error. This behavior is not very good. It prevents the user to collect all possible validation errors in a single validation process.

In order to change this default behavior, we can create our own error handler as shown in the following tutorial example:

/*
 * XsdSchemaSaxValidatorWithErrorHandler.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import javax.xml.XMLConstants;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import javax.xml.validation.Validator;
import java.io.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ErrorHandler;
class XsdSchemaSaxValidatorWithErrorHandler {
  private static int errorCount = 0;
  public static void main(String[] a) {
    if (a.length<2) {
      System.out.println("Usage:");
      System.out.println("java XsdSchemaValidator schema_file_name "
        + "xml_file_name");
    } else {
      String schemaName = a[0];
      String xmlName = a[1];
      Schema schema = loadSchema(schemaName);
      validateXml(schema, xmlName);
    }
  }
  public static void validateXml(Schema schema, String xmlName) {
    try {
      // creating a Validator instance
      Validator validator = schema.newValidator();
      System.out.println();
      System.out.println("Validator Class: "
        + validator.getClass().getName());

      // setting my own error handler
      validator.setErrorHandler(new MyErrorHandler());

      // preparing the XML file as a SAX source
      SAXSource source = new SAXSource(
        new InputSource(new java.io.FileInputStream(xmlName)));

      // validating the SAX source against the schema
      validator.validate(source);
      System.out.println();
      if (errorCount>0) {
        System.out.println("Failed with errors: "+errorCount);
      } else {
        System.out.println("Passed.");
      } 

    } catch (Exception e) {
      // catching all validation exceptions
      System.out.println();
      System.out.println(e.toString());
    }
  }
  public static Schema loadSchema(String name) {
    Schema schema = null;
    try {
      String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
      SchemaFactory factory = SchemaFactory.newInstance(language);
      schema = factory.newSchema(new File(name));
    } catch (Exception e) {
      System.out.println(e.toString());
    }
    return schema;
  }
  static class MyErrorHandler implements ErrorHandler {
    public void fatalError( SAXParseException e )
       throws SAXException {
      System.out.println(e.toString());
      throw e;
    }
    public void error( SAXParseException e ) throws SAXException {
      System.out.println(e.toString());
      errorCount++;
      // continue with validatin process
      // throw e;
    }
    public void warning( SAXParseException e ) throws SAXException {
      System.out.println(e.toString());
    }
  }
}

Now try this new validator on the XML file, first_html_extra_attribute.xml:

>javac XsdSchemaSaxValidatorWithErrorHandler.java

>java XsdSchemaSaxValidatorWithErrorHandler first_html.xsd
   first_html_extra_attribute.xml

org.xml.sax.SAXParseException: cvc-type.3.1.1: 
Element 'body' is a simple type,
so it cannot have attributes, excepting those whose namespace name
is identical to 'http://www.w3.org/2001/XMLSchema-instance'
and whose [local name] is one of 'type', 'nil', 'schemaLocation'
or 'noNamespaceSchemaLocation'. However, the attribute, 'bgcolor' 
was found.

org.xml.sax.SAXParseException: cvc-type.3.1.2: 
Element 'body' is a simple type,
so it must have no element information item [children].

Failed with errors: 2

We have a much better XSD schema validator now. You could use it for your real XML applications.

Sections in This Chapter

Standard Steps to Validate XML Docuements Against a Schema

XSD Schema File Loader - XsdSchemaLoader.java

XSD Schema File Loading Errors

XSD Schema XML DOM Validator - XsdSchemaDomValidator.java

XSD Schema XML DOM Validation Errors

XSD Schema XML DOM Validator with Error Handler

XSD Schema XML SAX Validator - XsdSchemaSaxValidator.java

XSD Schema XML SAX Validation Errors

XSD Schema XML SAX Validator with Error Handler

XSD Schema XML Validator - Final Version

Dr. Herong Yang, updated in 2007
XSD Schema XML SAX Validator with Error Handler