5.6.4 Sample Program When Using the DOM parser
This section describes a sample program for validating XML documents using the DOM parser, how the sample program is executed, and the execution results.
- Organization of this subsection
(1) Sample program (SampleValidateDOM.java)
The following shows the sample program (SampleValidateDOM.java) when using the DOM parser:
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import java.io.*;
public class SampleValidateDOM implements ErrorHandler{
public static final void main(String[] argv){
if (argv.length != 2) {
System.out.println(
"Usage: java SampleValidateDOM <xml_file> <schema_file>");
System.exit(1);
}
try{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
dbf.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaSource",
argv[1]);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new SampleValidateDOM());
Document doc = db.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");
}
}
(2) Execution result of the sample program
The execution result of this sample program is output to the standard output. The following shows the content of the standard output:
- When purchaseOrder.xml is specified for validation
Validation OK
- When purchaseOrder-fail.xml is specified for validation
**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