I found it is possible to do such a thing using the
javax.xml.validation package of Java 1.5:
private class ValidationErrorHandler extends DefaultHandler {
private List exList = new ArrayList();
public SAXParseException getFirstSaxParseException() {
return
(exList.size()==0?null
SAXParseException)exList.get(0));
}
public boolean validationError() {
return (exList.size()> 0);
}
public void error(SAXParseException exception) throws SAXException
{
exList.add(exception);
}
public void fatalError(SAXParseException exception) throws
SAXException {
exList.add(exception);
}
public void warning(SAXParseException exception) throws
SAXException {
}
}
public void validateDocument(Document doc, String xsd) throws
SAXException, IOException {
SchemaFactory factory = SchemaFactory.newInstance
(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(new File(xsd));
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
ValidationErrorHandler errHandler = new ValidationErrorHandler();
validator.setErrorHandler(errHandler);
validator.validate(new DOMSource(doc));
if (errHandler.validationError()) {
throw errHandler.getFirstSaxParseException();
}
}