有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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>

我试过的

环境

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) 个答案

  1. # 1 楼答案

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

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

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

    另见

    • 功能^{}用于DTD验证