Tag Archives: validation

Using Jing for Relax NG validation

I just ant to jot down how to programmatically use Jing for Relax NG validation. It has a simple API but I could not find any description besides the JavaDoc. It took me some time to figure out how to use it.

If you want to validate a XML file, just use ValidationDriver. If you have a DOM Document or StAX source, just do the following

//we are using Relax NG compact format
SchemaReader schemaReader = CompactSchemaReader.getInstance();

//schema can be reused, it's thread safe
Schema schema = schemaReader.createSchema(ValidationDriver.fileInputSource(new File("your_schema.txt)), PropertyMap.EMPTY);

//can use different error handler here (try DraconianErrorHandler http://www.thaiopensource.com/relaxng/api/jing/com/thaiopensource/xml/sax/DraconianErrorHandler.html)
ErrorHandler seh = new ErrorHandlerImpl();
PropertyMapBuilder  builder = new PropertyMapBuilder();
builder.put(ValidateProperty.ERROR_HANDLER, seh);
//Validator is NOT thread safe
Validator validator = schema.createValidator(builder.toPropertyMap());
Source source = ...//your XML source

TransformerFactory.newInstance().newTransformer().transform(source, new SAXResult(validator.getContentHandler()));

And that’s it.