在搜索了针对 XSD 验证我的 XML 的最佳方法之后,我遇到了 java.xml.validator。
我首先使用 API 中的示例代码并添加我自己的 ErrorHandler
// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("instance.xml"));
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(new File("mySchema.xsd"));
Schema schema = factory.newSchema(schemaFile);
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// Add a custom ErrorHandler
validator.setErrorHandler(new XsdValidationErrorHandler());
// validate the DOM tree
try {
validator.validate(new DOMSource(document));
} catch (SAXException e) {
// instance document is invalid!
}
...
private class XsdValidationErrorHandler implements ErrorHandler {
@Override
public void warning(SAXParseException exception) throws SAXException {
throw new SAXException(exception.getMessage());
}
@Override
public void error(SAXParseException exception) throws SAXException {
throw new SAXException(exception.getMessage());
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw new SAXException(exception.getMessage());
}
}
这工作正常,但是,传递给我的 XsdValidationErrorHandler 的消息并没有给我任何指示文档中有问题的 XML 的确切位置:
"org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'X'. One of '{Y}' is expected."
有没有办法让我覆盖或插入 Validator 的另一部分,以便我可以定义自己的错误消息发送到 ErrorHandler 而无需重写所有代码?
我应该使用不同的库吗?