使用java.xml.validator在XSD上验证XML时如何获得更具体的错误

Lev*_*ity 9 java xml validation xsd

在搜索了针对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());
    }
}
Run Code Online (Sandbox Code Playgroud)

这样可以正常工作,但是,传递给我的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."
Run Code Online (Sandbox Code Playgroud)

有没有办法让我覆盖或插入Validator的另一部分,这样我就可以定义自己发送给ErrorHandler的错误消息,而不必重写所有代码?

我应该使用不同的图书馆吗?

Ton*_*son 9

尝试捕获SaxParseException,它是SaxException的后代.如果你得到其中一个,它有方法getLineNumber(),getColumnNumber()等.