You could do something like the following where after the document is parser the resulting DOM is validated against the XML schema. You can set an instance of ErrorHandler
so that you can choose what to do with an validation errors.
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse(args[1]);
DOMSouce source = new DOMSource(document);
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("customer.xsd"));
Validator validator = schema.newValidator();
validator.setErrorHandler(new MyErrorHandler());
validator.validate(source);
}
}
Alternatively you could call setSchema
on the DocumentBuilderFactory
so that validation will happen during the parse, but this isn't supported by all DOM parsers:
For More Information
Below is a link to an example from my blog where this schema validation approach is used. In that example a JAXBSource
instead of a DOMSource
is used, but everything else is the same.