Abbey Workshop | ||||||||||
This tip is an example Java program for validating an XML file using an W3C XML Schema. This example uses Sun JAXP 1.2 API and JDK 1.4.0. JAXP 1.2 uses Apache Xerces as its underlying XML parser.
Note: This tip is current at the time of this writing. However, the XML standards are evolving daily and the parsing code may change anytime a new standard is introduced.
To make this example work, you must download and install the latest JAX Pack from Sun at http://java.sun.com/xml.
Download source for: SimpleSchema.java
Note:The following are sample XML files you can use to test the class.
View: todo.xml | todo.xsd | todoBad.xml
Download: todo.xml | todo.xsd | todoBad.xml
There are a couple of differences you will see right off the bat from a standard XML parser. Lines 15-18 define constants for parser features we want to use in our program. The JAXP_SCHEMA_LANGUAGE constant is used to define the language the schema is written in. The W3C_XML_SCHEMA constant identifies W3C XML Schema as the language we will be using to validate. The JAXP_SCHEMA_SOURCE constant is used when you which to specify a schema document different from the one specified in the XML document. We are not using this constant in this example.
Next, look at the SimpleSchema() constructor (line 21) for the key configuration steps used in creating our parsing object.
The parser is invoked on line 55. This method call parses the file and calls the ErrorHandler whenever an error is encountered.
Line 85-107. This is the error handling code. It is pretty simple really. Create warning(), error(), and fatalError() methods as shown. The appropriate method is called depending on the error generated. Warnings and errors will not stop parsing, however, fatal errors will.
Copyright © Abbey Workshop 2006