Skip navigation
2012

Actual XSD validation is a bit more harder, then regular XML file validation. Au contraire to popular believe

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setErrorHandler(new ErrorHandlerImpl());
schemaFactory.setResourceResolver(new XMLResourceResolver());
schemaFactory.newSchema(xsd);

does not validate a schema. It'll quietly create a schema object even if the schema itself is invalid.

 

To really validate the schema, you really must use a validator. So

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse(xsd);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setErrorHandler(new ErrorHandlerImpl());
schemaFactory.setResourceResolver(new XMLResourceResolver());
//Schema schema = schemaFactory.newSchema(new URL("http://www.w3.org/2001/XMLSchema.xsd"));
// make sure we do not use any internet resources
Schema schema = schemaFactory.newSchema(resource("schema/XMLSchema.xsd"));
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));

must be done to do the trick.

 

Actually it is exactly the same as XML file validation.

Filter Blog

By date:
By tag: