我正在研究模式验证。目的是获取一个XSD文件,并针对该文件验证传入的文档。如果有错误,我想捕获所有错误。
我在ErrorHandler中仅收到第一个错误,然后处理结束。互联网上有很多人问同样的问题,答案似乎总是我在做什么(创建自定义错误处理程序)。
此外,ErrorHandler接口的文档中还应说明错误方法的工作原理:
/**
* <p>The SAX parser must continue to provide normal parsing
* events after invoking this method: it should still be possible
* for the application to process the document through to the end.
* If the application cannot do so, then the parser should report
* a fatal error even if the XML recommendation does not require
* it to do so.</p>
*/
请注意,这是一个Java 13示例,但没有真正的必要(除了简洁的xml文本定义之外)。
private String drugValidationSchema = """
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.company.com/Drug"
xmlns:apins="https://www.company.com/Drug" elementFormDefault="qualified">
<element name="drugRequest" type="apins:drugRequest"></element>
<element name="drugResponse" type="apins:drugResponse"></element>
<complexType name="drugRequest">
<sequence>
<element name="id" type="int"></element>
</sequence>
</complexType>
<complexType name="drugResponse">
<sequence>
<element name="id" type="int"></element>
<element name="drugClass" type="string"></element>
<element name="drugName" type="string"></element>
</sequence>
</complexType>
</schema>
""";
// This document has 3 errors in it based on the schema above:
// 1) idx instead of id
// 2) dugClass instead of drugClass
// 3) dugName instead of drugName
private String badDrugResponseXml = """
<?xml version="1.0" encoding="UTF-8"?>
<apins:drugResponse xmlns:apins="https://www.company.com/Drug" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.company.com/Drug Drug.xsd ">
<apins:idx>1</apins:idx>
<apins:dugClass>opioid</apins:dugClass>
<apins:dugName>Buprenorphine</apins:dugName>
</apins:drugResponse>
""";
/**
* This test does nothing but send the desired files into the validation
* process. The goal is for the validation process to output 3 errors.
* For reasons I don't understand, it will only output the first one and
* stop the processing.
*/
@Test
void testWithValidator() {
System.out.println("Test an entry with multiple errors: " + validateXMLSchema(drugValidationSchema, badDrugResponseXml));
Assertions.assertTrue(true);
}
/**
* This validator process seems to always stop after the first error is encountered.
*
* @param xsdPath the actual XSD content as String
* @param xmlPath the actual xml document text as String.
* @return True if there are no errors, false otherwise. (planning to return details)
*/
static boolean validateXMLSchema(String xsdPath, String xmlPath){
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(new StringReader(xsdPath)));
Validator validator = schema.newValidator();
List<Exception> exceptions = new ArrayList<>();
// Add a custom handler to the validator. The goal is to continue processing
// the document so that ALL errors are captured.
validator.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) {
exceptions.add(exception);
}
@Override
public void fatalError(SAXParseException exception) {
exceptions.add(exception);
}
@Override
public void error(SAXParseException exception) {
exceptions.add(exception);
}
});
validator.validate(new StreamSource(new StringReader(xmlPath)));
if (exceptions.size() > 0) {
for (Exception ex : exceptions) {
System.out.println("Error found: " + ex.getMessage());
}
}else {
System.out.println("No errors.");
}
} catch (SAXException | IOException e) {
System.out.println("Exception: "+e.getMessage());
return false;
}
return true;
}
正如评论所暗示的,在调试中很明显,第一个错误是通过自定义错误处理程序的结果报告的,但是处理不会继续并找到随后的两个错误。
答案 0 :(得分:0)
答案并不简单,但请忍受...
我与一个实施完全兼容的验证XML解析器的团队一起工作。我问他们这个确切的功能。他们解释说,两种情况可能会导致标签名称不正确/异常(同一件事):
a)在xsd中正确位置的标签名称不正确
b)正确的标签名称在xsd中的错误位置
当人们要求使用此功能时,他们几乎总是在考虑方案a)。 XSD非常简单(XML文档中的可变性非常有限),对于人类读者来说,“意外”的标签名是错字是“显而易见的”。不幸的是,XSD规范允许多种类型的可变性。您可以使用xs:any(通配符),选择组,无序组,可选元素,具有各种类型的限制的复杂类型扩展等。如果XSD非常“开放”,则意外的标记名根本不是很明显一个简单的错字。在一般情况下,尝试继续将毫无意义,因为XML解析器不知道从何处继续进行解析。
只有在一种情况下,XML处理器可以发出验证错误,并且安全在所有情况下都可以继续解析 。如果标记/属性的简单值不符合xsd:facet限制,则可以报告错误并继续。解析器没有在XSD中丢失其“上下文”,因为元素的名称都已成功匹配。
您可能会想参考您的示例并说“但就我而言,解析可以安全地继续”。您可能是正确的,但我不知道有任何XML解析器能够针对不匹配的标记名区分“安全继续”和“不安全继续”两种情况。