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 use 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-2018 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 validation process
      // throw e;
    }
    public void warning( SAXParseException e ) throws SAXException {
      System.out.println(e.toString());
    }
  }
}

Let's try it with JDK on first_html_extra_attribute.xml:

herong> java XsdSchemaSaxValidatorWithErrorHandler \
   first_html.xsd first_html_extra_attribute.xml

Validator Class:
   com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorImpl

org.xml.sax.SAXParseException; lineNumber: 3; columnNumber: 25;
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; lineNumber: 5; columnNumber: 8;
cvc-type.3.1.2: Element 'body' is a simple type, so it must have
no element information item [children].

Failed with errors: 2

Nice. XsdSchemaSaxValidatorWithErrorHandler.java produces error messages with line number and column number, better than XsdSchemaDomValidatorWithErrorHandler.java.

Table of Contents

 About This Book

 Introduction of XML (eXtensible Markup Language)

 XML File Syntax

 XML File Browsers

 XML-JSON Document Conversion

 DOM (Document Object Model) Programming Interface

 SAX (Simple API for XML) Programming Interface

 DTD (Document Type Definition) Introduction

 Syntaxes of DTD Statements

 Validating an XML Document against the Specified DTD Document Type

 XSD (XML Schema Definition) Introduction

 Syntaxes of XSD Statements

Validating XML Documents Against Specified XML Schemas

 XSD Schema Validator on XML DOM Object

 XSD Schema Validator on XML DOM Object - Errors

XSD Schema Validator on XML SAX Object

 SAXParseException - 'xsi:noNamespaceSchemaLocation' Not Allowed

 Validating XML Linked with XSD using XMLReader

 XSL (Extensible Stylesheet Language) Introduction

 Java Implementation of XSLT

 XSLT (XSL Transformations) Introduction

 XPath (XML Path) Language

 XSLT Elements as Programming Statements

 Control and Generate XML Element in the Result

 PHP Extensions for XML Manipulation

 Processing XML with Python Scripts

 XML Notepad - XML Editor

 XML Tools Plugin for Notepad++

 XML Plugin Packages for Atom Editor

 XML 1.1 Changes and Parsing Examples

 Archived Tutorials

 References

 Full Version in PDF/EPUB