SAXパーサを使用してXML文書を検証する場合のサンプルプログラム,サンプルプログラムの実行方法,および実行結果について説明します。
SAXパーサを使用する場合のサンプルプログラム(SampleValidateSAX.java)を次に示します。
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");
}
}
このサンプルプログラムの実行結果は標準出力に出力されます。標準出力の内容を次に示します。
Validation OK