One of the main advantages of validation is that we can combine it with standard parsers like SAX. In this case, while handling SAX event we will not care whether the document is valid or not. Validator will check it for us. And we'll receive SAX events from already validated XML content. Example bellow shows how to insert JAXP validation between source XML-file and SAX-parser:

 import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

 * A sample application which shows how to perform a
 * XML document validation while parsing XML with SAX.

public class Test {
  public static void main(String[] args) {
    try {
      // create schema by from an XSD file:
      String schemaLang = "";
      SchemaFactory jaxp = SchemaFactory.newInstance(schemaLang);
      Schema schema = jaxp.newSchema(new StreamSource("sample.xsd"));
      // prepare document validator:
      Validator validator = schema.newValidator();

      // prepare SAX handler and SAX result receiving validate data:
      SaxHandler handler = new SaxHandler();
      SAXResult sax = new SAXResult(handler);

      // at last send valid data to out SAX handler:
      SAXSource source = new SAXSource(new InputSource("sample.xml"));
      validator.validate(source, sax);

    }catch (SAXException ex) {
      // we are here if the document is not valid:
      // ... process validation error...
    } catch (Exception ex) {

  // our SAX handler receiving validated data:
  private static final class SaxHandler extends DefaultHandler {
    // ...

Parent Category: Java SE Tips