XSD Schema Validator on XML SAX Object

This section provides a tutorial example on how to load a XSD schema, create an XSD validator and validate an XML SAXSource object.

Another way to used the Validator object created from a loaded XSD file is to apply it on a SAXSource object representing an XML file. Here is a tutorial example program called XsdSchemaDomValidatorWithErrorHandler.java:

/* XsdSchemaSaxValidatorWithErrorHandler.java
 - Copyright (c) 2014, HerongYang.com, 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());
    }
  }
}

Let's try it with JDK 1.8:

>java XsdSchemaSaxValidatorWithErrorHandler 
   dictionary.xsd dictionary_invalid_xsd.xml

Validator Class: 
   com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorImpl
   
org.xml.sax.SAXParseException; lineNumber: 7; columnNumber: 22; 
   cvc-datatype-valid.1.2.1: 'yes' is not a valid value for 'boolean'.

org.xml.sax.SAXParseException; lineNumber: 7; columnNumber: 22; 
   cvc-attribute.3: The value 'yes' of attribute 'acronym' on element 
   'word' is not valid with respect to its type, 'boolean'.

org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 31; 
   cvc-pattern-valid: Value '23-Dec-2003' is not facet-valid with 
   respect to pattern '\p{Nd}{4}-\p{Nd}{2}-\p{Nd}{2}' for type 
   '#AnonType_dateupdateType'.

org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 31; 
   cvc-attribute.3: The value '23-Dec-2003' of attribute 'date' on 
   element 'update' is not valid with respect to its type, 'null'.
   
org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 10; 
   The content of elements must consist of well-formed character data
   or markup.

Nice. We are getting same errors as XMLReaderValidator2.java, except that error messages are presented differently.

Last update: 2014.

Table of Contents

 About This JDK Tutorial Book

 Downloading and Installing JDK 1.8.0 on Windows

 Downloading and Installing JDK 1.7.0 on Windows

 Downloading and Installing JDK 1.6.2 on Windows

 Java Date-Time API

 Date, Time and Calendar Classes

 Date and Time Object and String Conversion

 Number Object and Numeric String Conversion

 Locales, Localization Methods and Resource Bundles

 Calling and Importing Classes Defined in Unnamed Packages

 HashSet, Vector, HashMap and Collection Classes

 Character Set Encoding Classes and Methods

 Character Set Encoding Maps

 Encoding Conversion Programs for Encoded Text Files

 Socket Network Communication

 Datagram Network Communication

 DOM (Document Object Model) - API for XML Files

 SAX (Simple API for XML)

 DTD (Document Type Definition) - XML Validation

XSD (XML Schema Definition) - XML Validation

 XML XSD Schema Validation

 XML XSD Schema Validation Test Result

 XML XSD Schema Validation with Xerces

 XSD Validation Failed with SAXParserFactory

XSD Schema Validator on XML SAX Object

 XSL (Extensible Stylesheet Language)

 Message Digest Algorithm Implementations in JDK

 Private key and Public Key Pair Generation

 PKCS#8/X.509 Private/Public Encoding Standards

 Digital Signature Algorithm and Sample Program

 "keytool" Commands and "keystore" Files

 KeyStore and Certificate Classes

 Secret Key Generation and Management

 Cipher - Secret Key Encryption and Decryption

 The SSL (Secure Socket Layer) Protocol

 SSL Socket Communication Testing Programs

 SSL Client Authentication

 HTTPS (Hypertext Transfer Protocol Secure)

 Outdated Tutorials

 References

 PDF Printing Version