java SAXParser未调用“schema_reference.4:读取架构文档失败”上的警告
我正在尝试使用SAXParser
验证XML。XML故意指向一个不存在的模式文档,但SAX并没有像我预期的那样调用警告
使用Eclipse的验证机制验证XML时,它会正确地用警告标记文件:
schema_reference.4: Failed to read schema document 'schema', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
当执行测试方法时,既不向打印System.out
,也不抛出SAXException
(或任何Exception
)
试验方法
@Test
public void testSaxParser_missingSchema() throws ParserConfigurationException, SAXException, IOException {
// Arrange
final String resourcesFolder = "src/test/resources/XML_missing_schema.xml";
// Act
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new LocalErrorHandler());
xmlReader.parse(toBeValidated); // does not throw anything, test passes
}
类LocalErrorHandler
class LocalErrorHandler implements ErrorHandler {
@Override
public void warning(SAXParseException exception) throws SAXException {
System.out.println(exception);
throw exception;
}
@Override
public void error(SAXParseException exception) throws SAXException {
System.out.println(exception);
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println(exception);
throw exception;
}
}
src/test/resources/XML\u缺少\u架构。xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Type xsi:schemaLocation="namespace schema"
xmlns="namespace" xmlns:schemaNs="namespace/schemaNs"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</Type>
我试过的
- 故意抛出
SAXParseException
会导致测试失败李> - 按照https://docs.oracle.com/javase/8/docs/api/org/xml/sax/ErrorHandler.html使用
Known Implementing Classes
作为错误处理程序。它们都不能处理警告,因此不会发生任何事情李> - 不调用
spf.setNamespaceAware(true);
没有什么区别李>
环境
C:\eclipse\jdk8\bin>java.exe -version
openjdk version "1.8.0_265"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_265-b01)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.265-b01, mixed mode)
C:\eclipse>type .eclipseproduct
name=Eclipse Platform
id=org.eclipse.platform
version=4.15.0
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
# 1 楼答案
通过将其feature设置为
true
来启用XML架构验证:默认值为false,因此如果没有该调用,就不会执行XSD验证
另见