All about JAXP, Part 1
By Brett McLaughlin
2005-07-15
Performing validation
In Java 5.0 (and JAXP 1.3), JAXP introduces a new way to validate documents. Instead of simply using the setValidating() method on a SAX or DOM factory, validation is broken out into several classes within the new javax.xml.validation package. I would need more space than I have in this article to detail all the nuances of validation -- including W3C XML Schema, DTDs, RELAX NG schemas, and other constraint models -- but if you already have some constraints, it's pretty easy to use the new validation model and ensure that your document matches up with them. Redundancy isn't always good One thing you should not do is use setValidating(true) and the javax.xml.validation package. You'll get some nasty errors, and most of them are hard to track down. It's best to make a habit of never calling setValidating() -- which defaults to false -- and to use the new JAXP validation framework instead. |
First, convert your constraint model -- presumably a file on disk somewhere -- into a format that JAXP can use. Load the file into a Source instance. (I'll cover Source in more detail in Part 2; for now, just know that it represents a document somewhere, on disk, as a DOM Document or just about anything else.) Then, create a SchemaFactory and load the schema using SchemaFactory.newSchema(Source), which returns a new Schema object. Finally, with this Schema object, create a new Validator object with Schema.newValidator(). Listing 5 should make everything I've just said much clearer: Listing 5. Using the JAXP validation framework
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(args[0]));
// Handle validation
SchemaFactory constraintFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source constraints = new StreamSource(new File(args[1]));
Schema schema = constraintFactory.newSchema(constraints);
Validator validator = schema.newValidator();
// Validate the DOM tree
try {
validator.validate(new DOMSource(doc));
System.out.println("Document validates fine.");
} catch (org.xml.sax.SAXException e) {
System.out.println("Validation error: " + e.getMessage());
}
|
This is pretty straightforward once you get the hang of it. Type this code in yourself, or check out the full listing (see Download).
Tutorial Pages:
»
XML processing toolkit facilitates parsing and validation
»
JAXP: API or abstraction?
»
Starting with SAX
»
Dealing with DOM
» Performing validation
»
Changing the parser
»
Summary
»
Resources
First published by IBM developerWorks
|

|