I'm trying to validate an XML using SAXParser
. The XML is deliberately pointing to a non-existent schema document but SAX does not invoke a warning, as I would expect it to.
When validating the XML using Eclipse's validate mechanisms, it correctly flags the file with a warning:
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>.
When executing the test method, neither System.out
is printed to, nor a SAXException
(or any Exception
, for that matter) is thrown.
The test method
@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>
SAXParseException
causes the test to fail.Known Implementing Classes
as ErrorHandler as per https://docs.oracle.com/javase/8/docs/api/org/xml/sax/ErrorHandler.html. None of there handle warnings and thus nothing happens.spf.setNamespaceAware(true);
does not make a difference.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>
Enable XML Schema validation by setting its feature to true
:
xmlReader.setFeature("http://apache.org/xml/features/validation/schema", true);
The default is false, so without that call, no XSD validation is performed.
See also
http://xml.org/sax/features/validation
for DTD validation.