XSD Tutorials - Herong's Tutorial Examples - Version 5.10, by Dr. Herong Yang

XSD Schema XML DOM 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:

/*
 * XsdSchemaDomValidatorWithErrorHandler.java
 - Copyright (c) 2013, HerongYang.com, All Rights Reserved.
 */
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import javax.xml.validation.Validator;
import javax.xml.transform.dom.DOMSource;
import java.io.File;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ErrorHandler;
class XsdSchemaDomValidatorWithErrorHandler {
  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);
      Document document = parseXmlDom(xmlName);
      validateXml(schema, document);
    }
  }
  public static void validateXml(Schema schema, Document document) {
    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());

      // validating the document against the schema
      validator.validate(new DOMSource(document));
      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;
  }
  public static Document parseXmlDom(String name) {
    Document document = null;
    try {
      DocumentBuilderFactory factory 
         = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(new File(name));
    } catch (Exception e) {
      System.out.println(e.toString());
    }
    return document;
  }
  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 XsdSchemaDomValidatorWithErrorHandler.java

>java XsdSchemaDomValidatorWithErrorHandler 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.

Last update: 2013.

Table of Contents

 About This Book

 Introduction to XML Schema

 XML Editor and Schema Processor - XMLPad

 Java API for XML Processing - JAXP

JAXP - XML Schema (XSD) Validation

 Standard Steps to Validate XML Documents 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

 Xerces2 Java Parser - Java API of XML Parsers

 Using Xerces2 Java API

 XML Schema Language - Basics

 Introduction of XSD Built-in Datatypes

 "string" and Its Derived Datatypes

 "decimal" and Its Derived Datatypes

 "dateTime" and Its Related Datatypes

 Miscellaneous Built-in Datatypes

 Facets, Constraining Facets and Restriction Datatypes

 "simpleType" - Defining Your Own Simple Datatypes

 Complex Element Declaration

 Identity-Constraints: unique, key and keyref

 Assertion as Custom Validation Rules

 XML Schema Location and Namespace in XML Documents

 Overriding Element Types in XML Documents

 Linking Multiple Schema Documents Together

 Glossary

 References

 PDF Printing Version

XSD Schema XML DOM Validator with Error Handler - Updated in 2014, by Dr. Herong Yang