Thursday 26 July 2007

quicky: xml schema validation using dom4j

I believe I have spend to much time with xml schema validation using dom4j, considering what I think should be a trival operation.
I was not capable of finding the howto on this subject, so I will provide my own. Mosty as a note to myself the next time I have to do schema validation.

public Document parseXMl(String xml) throws Exception {
URL resource = getClass().getResource("/my-schema.xsd");
SAXReader reader = new SAXReader(true);
reader.setFeature("http://apache.org/xml/features/validation/schema", true);
reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", new File(resource.getFile()));
reader.setErrorHandler(new ErrorHandlerImpl());
InputSource source = new InputSource(new StringReader(xml));
source.setEncoding("UTF-8");
return reader.read(source);
}