微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决SAXParser 不会在“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
}

类 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 验证。

另见

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?