import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class Schema1{ //Constants when using XML Schema for SAX parsing. static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; //main public static void main(String[] args) { String msg,xml,xsd; if(args.length!=2){ xml = "letter.xml"; xsd = "letter.xsd"; System.out.println("No arguments found:\nUsage: xmlFile xsdFile" + "\nUsing letter.xml letter.xsd"); }else{ xml = args[0]; xsd = args[1]; } if(isValid("letter.xml","letter.xsd")){ msg = "File is valid"; }else{ msg = "ERROR! INVALID FILE"; } System.out.println(msg); } //SAX parsing public static boolean isValid(String source, String schema){ try { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(true); SAXParser sp = spf.newSAXParser(); sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); sp.setProperty(JAXP_SCHEMA_SOURCE, schema); MyDefaultHandler dh = new MyDefaultHandler(); sp.parse(source, dh); return (dh.isValid)?true:false; } catch(SAXException se) { se.printStackTrace(); }catch (Exception e) { System.err.println(e); } return false; } } //Custom error hanler to print errors and return isValid class MyDefaultHandler extends DefaultHandler { //flag to check if the xml document was valid public boolean isValid = true; //Receive notification of a recoverable error. public void error(SAXParseException se) { setValidity(se); } //Receive notification of a non-recoverable error. public void fatalError(SAXParseException se) { setValidity(se); } //Receive notification of a warning. public void warning(SAXParseException se) { setValidity(se); } private void setValidity(SAXParseException se){ isValid = false; System.out.println(se.toString()); } }