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

XSD Schema XML Validator - Final Version

This section describes the final version of the XML Schema (XSD) validator using the JAXP API.

The last XML Schema (XSD) validator, XsdSchemaSaxValidatorWithErrorHandler.java, needs one more enhancement to make to more user friendly. The error message needs to be printed out with the location where the error was detected. Here is the final version of my XML Schema validator using JAXP API, XsdSchemaValidator.java:

/*
 * XsdSchemaValidator.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 XsdSchemaValidator {
  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();

      // 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;
  }
  private static class MyErrorHandler implements ErrorHandler {
    public void warning(SAXParseException e) throws SAXException {
       System.out.println("Warning: "); 
       printException(e);
    }
    public void error(SAXParseException e) throws SAXException {
       System.out.println("Error: "); 
       printException(e);
    }
    public void fatalError(SAXParseException e) throws SAXException {
       System.out.println("Fattal error: "); 
       printException(e);
    }
    private void printException(SAXParseException e) {
      errorCount++;
      System.out.println("   Line number: "+e.getLineNumber());
      System.out.println("   Column number: "+e.getColumnNumber());
      System.out.println("   Message: "+e.getMessage());
      System.out.println();
    }
  }
}

Now try this final version on the XML file, first_html_extra_attribute.xml and the XSD file, first_html.xsd:

>javac XsdSchemaValidator.java

>java XsdSchemaValidator first_html.xsd first_html_extra_attribute.xml
Error:
   Line number: 3
   Column number: 25
   Message: 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.

Error:
   Line number: 5
   Column number: 8
   Message: cvc-type.3.1.2: Element 'body' is a simple type, so it 
   must have no element information item [children].

Failed with errors: 2

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 Validator - Final Version