// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class ValidateSchema {
    private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
    private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
    public static void testSchema(final String xmlfnm, final String xsdfnm) throws SAXException, IOException, ParserConfigurationException {
        System.out.printf("Validating %s against schema %s\n", xmlfnm, xsdfnm);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        SAXParser saxParser = factory.newSAXParser();
        saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        saxParser.setProperty(JAXP_SCHEMA_SOURCE, new File(xsdfnm));
        saxParser.parse(new File(xmlfnm), new DefaultHandler() {
            @Override
            public void error(SAXParseException ex) {
                System.out.println(ex.getMessage());
            }
            @Override
            public void warning(SAXParseException ex) {
                System.out.println(ex.getMessage());
            }
        });
    }
    public static void main(String[] args) throws Exception {
        testSchema("test4.xml", "test.xsd");
        testSchema("test5.xml", "test.xsd");
        testSchema("test6.xml", "test.xsd");
    }
}
