我有一个像下面这样的标准代码,可以针对xsd验证xml,但是它会在第一个错误时引发异常并停止。如何验证xml,但继续出现第一个和下一个错误,并在最后获得所有错误?可能吗?
public static void validate(File xml, InputStream xsd) { try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); StreamSource xmlFile = new StreamSource(xml); validator.validate(xmlFile); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
在Validator validator = schema.newValidator();和之间StreamSource xmlFile = new StreamSource(xml);添加此片段:
Validator validator = schema.newValidator();
StreamSource xmlFile = new StreamSource(xml);
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); } });
这样,validate()您将获得完整的异常列表之后,但是如果发生一个致命错误,则分析将停止…
validate()
编辑:JavaDoc说: _应用程序必须假定解析器调用此方法后该文档不可用,并且仅应出于收集其他错误消息的目的而继续(如果有的话):实际上, SAX解析器可以自由停止 调用此方法后, 报告其他事件 。_因此fatalError()可能会或可能不会导致解析停止。
fatalError()