Between Validator validator = schema.newValidator();
and StreamSource xmlFile = new StreamSource(xml);
add this fragment:
final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
validator.setErrorHandler(new ErrorHandler()
{
@Override
public void warning(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void fatalError(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void error(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
});
This way, after validate()
you'll get full list of exceptions, but if one fatal error occurs, the parsing stops...
EDIT: the JavaDoc says: The application must assume that the document is unusable after the parser has invoked this method, and should continue (if at all) only for the sake of collecting additional error messages: in fact, SAX parsers are free to stop reporting any other events once this method has been invoked. So fatalError()
may or may not cause the parsing to stop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…