| home / programming / xml / parser / 1 | [previous] [next] |
|
|
The Xerces-J SAX parser supports validation with the W3C XML Schema Language. By default, it reads the schema with which to validate documents from the xsi:schemaLocation and xsi:noNamespaceSchema Location attributes in the instance document. However, you can override these with the http://apache.org/xml/properties/schema/external-schemaLocation and http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation SAX properties. In this example, the documents being validated have namespaces, so we'll set http://apache.org/xml/properties/schema/external-schemaLocation to http://www.example.com/tvprogram.xsd. Then, we'll turn on schema validation by setting the http://apache.org/xml/features/validation/schema feature to true.

We'll also have to register an ErrorHandler to receive any validation errors that are detected. Because validity errors aren't necessarily fatal unless we make them so, we'll rethrow the SAXParseException passed to the error() method. Example 37-3 shows an appropriate Error Handler class.
Example 37-3 A SAX ErrorHandler That Makes Validity Errors Fatal

This ErrorHandler also needs to be installed with the parser.
parser.setErrorHandler(new ErrorsAreFatal());
Finally, the document can be parsed. The parser checks it against the schema as it parses. At the same time, the ContentHandler methods accumulate the data into the fields. Since SAX parsing interleaves parser operation with client code, all the data collected should be stored until the complete document has been validated. Only then can you be sure the document is valid and the information should be committed. Example 37-4 demonstrates one way to build a TVProgram object that stores this data. The constructor is private, so the only way to build such an object is by passing an InputStream containing a TVProgram document to the readTVProgram() method. The TVProgram object is actually created before the parsing starts. However, it's not returned to anything outside this class until the input document has been parsed and any constraints verified. If a constraint is violated, then an exception is thrown.
Example 37-4 A Program That Validates against a Schema

| home / programming / xml / parser / 1 | [previous] [next] |
Created: March 27, 2003
Revised: October 25, 2003
URL: http://webreference.com/programming/xml/parser/1