嗯,标题说明了一切。
我知道这不是阻塞调用,但我需要等待它完成验证才能进入下一个语句。
我该怎么做?
private class ErrorHandler extends DefaultHandler{
public SAXParseException ex = null;
public boolean errorOccured = false;
@Override
public void error(SAXParseException ex) {
this.ex = ex;
errorOccured = true;
}
@Override
public void fatalError(SAXParseException ex){
this.ex = ex;
errorOccured = true;
}
@Override
public void warning(SAXParseException ex){
}
}
答案 0 :(得分:2)
不确定你的意思是“我知道这不是阻止通话”。是什么让你这么想?
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);