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) 2013, 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 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

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