JAXP: How to validate a org.w3c.dom.Document against a XML Schema

6.5k views Asked by At

How to validate an (already parsed) org.w3c.dom.Document against a XML Schema using JAXP?

1

There are 1 answers

5
bdoughan On

You can use the javax.xml.validation APIs for this.

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
URL schemaURL = // The URL to your XML Schema; 
Schema schema = sf.newSchema(schemaURL); 
Validator validator = schema.newValidator();
DOMSource source = new DOMSource(xmlDOM);
validator.validate(source);

The example below demonstrates how to validate a JAXB object model against a schema, but you'll see it's easy to replace the JAXBSource with a DOMSource for DOM: