This section describes a tutorial example on how to the Xerces2 SAXParser class to validate an XML document assigned with an XSD file.
Note that tutorial examples given in this section were taken in 2002 using
JDK 1.4 and Xerces-J 2.3. But the example Java program can still run using JDK 1.6 and Xerces2 2.9.1
Xerces-J package can also be loaded by the SAXParserFactory.newInstance()
method. Here is my SAXValidator.java:
/**
* SAXValidator.java
* Copyright (c) 2002 by Dr. Herong Yang. All rights reserved.
*/
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
class SAXValidator {
public static void main(String[] args) {
String schemaFeature
= "http://apache.org/xml/features/validation/schema";
try {
File x = new File(args[0]);
SAXParserFactory f = SAXParserFactory.newInstance();
System.out.println(f.toString());
f.setValidating(true);
f.setFeature(schemaFeature,true);
SAXParser p = f.newSAXParser();
System.out.println(p.toString());
DefaultHandler h = new MyErrorHandler();
p.parse(x,h);
} catch (ParserConfigurationException e) {
System.out.println(e.toString());
} catch (SAXException e) {
System.out.println(e.toString());
} catch (IOException e) {
System.out.println(e.toString());
}
}
private static class MyErrorHandler extends DefaultHandler {
public void warning(SAXParseException e) throws SAXException {
System.out.println("Warning: ");
printInfo(e);
}
public void error(SAXParseException e) throws SAXException {
System.out.println("Error: ");
printInfo(e);
}
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("Fattal error: ");
printInfo(e);
}
private void printInfo(SAXParseException e) {
System.out.println(" Public ID: "+e.getPublicId());
System.out.println(" System ID: "+e.getSystemId());
System.out.println(" Line number: "+e.getLineNumber());
System.out.println(" Column number: "+e.getColumnNumber());
System.out.println(" Message: "+e.getMessage());
}
}
}
Note that the schema feature is set to the SAXParserFactory object, not to the SAXParser object.
org.apache.xerces.jaxp.SAXParserFactoryImpl@f72617
org.apache.xerces.jaxp.SAXParserImpl@173831b
... Same error messages as shown in the previous section ...
Note that the "xerces" implementation was loaded, and XSD validation was performed.