Saturday, June 26, 2010

Validate a document using JDom

Validate a document is easier in org.w3c.dom or even in JDom, just thanks to the usage of interfaces.
Here is a demo of how doing that:

public boolean validate(URL uschema) throws IOException {
try {
// 1. Lookup a factory for the W3C XML Schema language
SchemaFactory factory =
SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
// 2. Compile the schema.
// Here the schema is loaded from a java.io.File, but you could use
// a java.net.URL or a javax.xml.transform.Source instead.
// 3. Get a validator from the schema.
Schema schema = factory.newSchema(uschema);
Validator validator = schema.newValidator();
// 4. Parse the document you want to check.
//Source source = new StreamSource(in);
Source source = new org.jdom.transform.JDOMSource(document);
// 5. Check the document
validator.validate(source);
//System.out.println(file + " is valid.");
} catch (SAXException ex) {
this.validationMessage = ex.getMessage();
return false;
}
return true;
}