【发布时间】:2014-07-06 21:00:28
【问题描述】:
我正在使用 javax.xml.validation.Validator 类针对 XSD 架构验证内存中的 DOM 对象。每当我从中填充 DOM 的信息中存在某些数据损坏时,我都会在验证期间抛出 SAXParseException。
错误示例:
org.xml.SAXParseException: cvc-datatype-valid.1.2.1: '???"??[?????G?>???p~tn??~0?1]' 是不是“hexBinary”的有效值。
我希望有一种方法可以在我的内存 DOM 中找到此错误的位置并打印出有问题的元素及其父元素。我当前的代码是:
public void writeDocumentToFile(Document document) throws XMLWriteException {
try {
// Validate the document against the schema
Validator validator = getSchema(xmlSchema).newValidator();
validator.validate(new DOMSource(document));
// Serialisation logic here.
} catch(SAXException e) {
throw new XMLWriteException(e); // This is being thrown
} // Some other exceptions caught here.
}
private Schema getSchema(URL schema) throws SAXException {
SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Some logic here to specify a ResourceResolver
return schemaFactory.newSchema(schema);
}
我研究了Validator#setErrorHandler(ErrorHandler handler) 方法,但ErrorHandler 接口只让我接触到SAXParseException,它只公开错误的行号和列号。因为我使用的是内存中的 DOM,所以行号和列号都返回 -1。
有没有更好的方法来做到这一点?如果库为我提供了我正在寻找的功能,我真的不想在将它们添加到 DOM 之前手动验证字符串。
我正在使用 JDK 6 update 26 和 JDK 6 update 7,具体取决于此代码的运行位置。
编辑:添加此代码 -
validator.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
printException(exception);
throw exception;
}
@Override
public void error(SAXParseException exception) throws SAXException {
printException(exception);
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
printException(exception);
throw exception;
}
private void printException(SAXParseException exception) {
System.out.println("exception.getPublicId() = " + exception.getPublicId());
System.out.println("exception.getSystemId() = " + exception.getSystemId());
System.out.println("exception.getColumnNumber() = " + exception.getColumnNumber());
System.out.println("exception.getLineNumber() = " + exception.getLineNumber());
}
});
我得到了输出:
exception.getPublicId() = null
exception.getSystemId() = null
exception.getColumnNumber() = -1
exception.getLineNumber() = -1
【问题讨论】:
标签: java xml xml-validation