package demo; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.IOException; import java.io.InputStream; import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; /** * Class ValidDocument provides an XML document validated a schema. * @author David Morris */ public class ValidDocument { public Document build(InputStream xmlFile, String xmlSchema) throws JDOMException, IOException { // Create new SAXBuilder, using default parser SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", true); builder.setEntityResolver(new SchemaLoader()); // Uncommenting the following line ensures that the document received stands alone // builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); builder.setFeature( "http://apache.org/xml/features/validation/schema", true); builder.setProperty( "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "file:///" + xmlSchema); Document doc = builder.build(xmlFile); return doc; } public static void main(String[] args) { if (args.length < 2) { System.err.println( "Usage: java demo.ValidDocument "); } try { InputStream xmlFile = Thread .currentThread() .getContextClassLoader() .getResourceAsStream( args[0]); ValidDocument vd = new ValidDocument(); Document doc = vd.build(xmlFile, args[1]); // Output the document to System.out XMLOutputter outputter = new XMLOutputter(); outputter.output(doc, System.out); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.exit(0); } public class SchemaLoader implements EntityResolver { public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { if (systemId.toLowerCase().endsWith(".xsd")) { InputStream is = Thread .currentThread() .getContextClassLoader() .getResourceAsStream(systemId.substring(8)); // Drop file:/// return new InputSource(is); } else { return null; } } } }