SAXParser 不会在 "schema_reference.4: Failed to read schema document" 上调用警告

SAXParser does not invoke warning on "schema_reference.4: Failed to read schema document"

我正在尝试使用 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
}

Class 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_missing_schema.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>

我试过的

环境

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>

通过将其 feature 设置为 true 来启用 XML 模式验证:

xmlReader.setFeature("http://apache.org/xml/features/validation/schema", true);

默认值为 false,因此如果没有调用,则不会执行 XSD 验证。

另见