不确定“我知道这不是阻塞呼叫”是什么意思。什么让你有那个想法?
Validator.validate
是阻塞调用。
如果您想验证文档,然后检查错误,您可以创建自己的ErrorHandler
final Validator validator = schema.newValidator();
final List<SAXParseException> errors = new ArrayList<SAXParseException>();
validator.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException saxpe) throws SAXException {
//ignore, log or whatever
}
public void error(SAXParseException saxpe) throws SAXException {
errors.add(saxpe);
}
public void fatalError(SAXParseException saxpe) throws SAXException {
//parsing cannot continue
throw saxpe;
}
});
final Source source = new StreamSource(new File("my.xml"));
validator.validate(source);
if(!errors.isEmpty()) {
//there are errors.
}
或者您可以抛出错误以中止对第一个错误的验证
final Validator validator = schema.newValidator();
validator.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException saxpe) throws SAXException {
//ignore, log or whatever
}
public void error(SAXParseException saxpe) throws SAXException {
throw saxpe;
}
public void fatalError(SAXParseException saxpe) throws SAXException {
//parsing cannot continue
throw saxpe;
}
});
final Source source = new StreamSource(new File("my.xml"));
validator.validate(source);