This section describes a sample program for validating XML documents using the SAX parser, how the sample program is executed, and the execution result.
The following shows the sample program (SampleValidateSAX.java) when using the SAX parser:
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
public class SampleValidateSAX implements ErrorHandler{
public static final void main(String[] argv){
if (argv.length != 2) {
System.out.println(
"Usage: java SampleValidateSAX <xml_file> <schema_file>");
System.exit(1);
}
try{
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
sp.setProperty(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
sp.setProperty(
"http://java.sun.com/xml/jaxp/properties/schemaSource",
argv[1]);
XMLReader reader = sp.getXMLReader();
reader.setErrorHandler(new SampleValidateSAX());
reader.parse(argv[0]);
System.out.println("Validation OK");
}catch(ParserConfigurationException e){
e.printStackTrace();
}catch(SAXParseException e){
e.printStackTrace();
}catch(SAXException e){
System.out.println("Validation NG: " + e.getMessage());
}catch(IOException e){
e.printStackTrace();
}
}
public void warning(SAXParseException exception)
throws SAXException {
System.out.println("**Parsing Warning**\n" +
" Line: " +
exception.getLineNumber() + "\n" +
" URI: " +
exception.getSystemId() + "\n" +
" Message: " +
exception.getMessage());
}
public void error(SAXParseException exception)
throws SAXException{
System.out.println("**Parsing Error**\n" +
" Line: " +
exception.getLineNumber() + "\n" +
" URI: " +
exception.getSystemId() + "\n" +
" Message: " +
exception.getMessage());
throw new SAXException("Error encountered");
}
public void fatalError(SAXParseException exception)
throws SAXException {
System.out.println("**Parsing Fatal Error**\n" +
" Line: " +
exception.getLineNumber() + "\n" +
" URI: " +
exception.getSystemId() + "\n" +
" Message: " +
exception.getMessage());
throw new SAXException("Fatal Error encountered");
}
}
The execution result of this sample program is output to the standard output. The following shows the content of the standard output:
Validation OK
**Parsing Error**
Line: 33
URI: file:///folder-where-sample-is-stored/purchaseOrder-fail.xml
Message: KECX06063-E cvc-pattern-valid: Value '111144442222999955' is not facet-valid with respect to pattern '\d{16}' for type '#AnonType_creditNumber'.
Validation NG: Error encountered