JAXP Schema Validation in Java5 and Java6

I have had a little battle with schema validation of XML documents and thought I would share it with the world.

I wrote the below code on Java5, thinking this was a way of validating a piece of XML against a schema definition. And indeed, it does work on Java5:

SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setSchema(sf.newSchema(schemaUrl));
DocumentBuilder parser = dbf.newDocumentBuilder();
parser.parse(new InputSource(new CharArrayReader(xml.toCharArray())));

Only thing is, this does not validate on Java6. In fact, if I install an ErrorHandler on the DocumentBuilder that simply rethrows exceptions, the parsing will complain about the very first attribute it meets, even though the Schema allows it.

It took me a while, to figure out what to do. In the process, I debugged into both Apache and the com.sun…apache packages, to try and find out what was different with parser behaviour on Java6. In the end, it proved really simple. I just hard to learn to actually use the javax.xml.validation API instead. An API made for, … validation. Duuh! Here is the code, that works on both Java5 and Java6:

SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = sf.newSchema(schemaUrl);
Validator validator = schema.newValidator();
Source source = new StreamSource(new CharArrayReader(xml.toCharArray()));
validator.validate(source);

June 25, 2009  Tags: , , ,   Posted in: Programming

One Response

  1. Tech Per » Blog Archive » Tip: Debugging JAXP Internals - June 25, 2009

    [...] my latest battle with JAXP and Schema validation, I found out a little trick. It turns out, that implementation classes in JAXP use a debug flag to [...]

Leave a Reply