Reputation:
I have the following the following xml schema module.xsd:
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" >
<xs:element name="module2">
<xs:complexType>
<xs:sequence>
<xs:element name="temp" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
and I have the following xml document module.xml:
<module xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="module.xsd">
<init-param name="foo" value="boo"/>
</module>
And this the code I create parser:
Schema xmlSchema = null;
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
xmlSchema = schemaFactory.newSchema(getClass().getResource(MODULE_PATH));
if (xmlSchema==null){
System.out.println("Schema NULL");
}else{
System.out.println("Schema NOT NULL");
}
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setSchema(xmlSchema);
parserFactory.setValidating(true);
parserFactory.setNamespaceAware(true);
SAXParser saxParser = parserFactory.newSAXParser();
I get Schema NOT NULL
and my file is parsed without any probmes. But I wait the exception as the schema is wrong. What is my mistake?
Upvotes: 1
Views: 280
Reputation: 33000
If the parser encounters schema validations it will not throw an exception but report the violation to its ErrorHandler
which in most cases will be the DefaultHandler
passed to SaxParser.parse()
:
If you want validation errors thrown as exception then override DefaultHandler.error
:
saxParser.parse(new File("module.xml"), new DefaultHandler() {
public void error (SAXParseException e) throws SAXException {
throw e;
}
});
Upvotes: 0