1 2 import org.w3c.dom.ls.LSInput ; 3 import org.w3c.dom.ls.LSResourceResolver ; 4 import org.xml.sax.ErrorHandler ; 5 import org.xml.sax.SAXException ; 6 import org.xml.sax.SAXParseException ; 7 8 import javax.xml.transform.stream.StreamSource ; 9 import javax.xml.validation.Schema ; 10 import javax.xml.validation.SchemaFactory ; 11 import javax.xml.validation.Validator ; 12 import java.io.File ; 13 14 25 26 public class SchemaValidatorExample { 27 28 31 32 protected static class Handler implements ErrorHandler { 33 34 38 public void error(SAXParseException ex) { 39 System.err.println("At line " + ex.getLineNumber() + " of " + ex.getSystemId() + ":"); 40 System.err.println(ex.getMessage()); 41 } 42 43 47 48 public void fatalError(SAXParseException ex) { 49 System.err.println("At line " + ex.getLineNumber() + " of " + ex.getSystemId() + ":"); 50 System.err.println(ex.getMessage()); 51 } 52 53 57 public void warning(org.xml.sax.SAXParseException ex) { 58 System.err.println("At line " + ex.getLineNumber() + " of " + ex.getSystemId() + ":"); 59 System.err.println(ex.getMessage()); 60 } 61 62 } 63 64 69 70 protected static class Resolver implements LSResourceResolver { 71 72 83 84 public LSInput resolveResource(String type, String namespace, String publicId, String systemId, String baseURI) { 85 return null; 86 } 87 88 } 89 90 94 public static void main(String [] args) { 95 try { 96 if(args.length != 2){ 97 printUsage(); 98 return; 99 } 100 101 Handler handler = new Handler (); 102 103 SchemaFactory schemaFactory; 104 105 109 112 schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); 113 System.err.println("Loaded schema validation provider " + schemaFactory.getClass().getName()); 114 115 schemaFactory.setErrorHandler(handler); 116 Schema schemaGrammar = schemaFactory.newSchema(new File (args[0])); 118 119 System.err.println("Created Grammar object for schema : "+args[0]); 120 121 Resolver resolver = new Resolver (); 122 Validator schemaValidator = schemaGrammar.newValidator(); 124 schemaValidator.setResourceResolver(resolver); 125 schemaValidator.setErrorHandler(handler); 126 127 System.err.println("Validating "+args[1] +" against grammar "+args[0]); 128 schemaValidator.validate(new StreamSource (args[1])); 130 131 System.err.println("Validation successful"); 132 } catch (SAXException saxe) { 133 exit(1, "Error: " + saxe.getMessage()); 134 } catch (Exception e) { 135 e.printStackTrace(); 136 exit(2, "Fatal Error: " + e); 137 } 138 } 139 140 145 public static void exit(int errCode, String msg) { 146 System.err.println(msg); 147 System.exit(errCode); 148 } 149 150 public static void printUsage(){ 151 System.err.println("Usage : SchemaValidatorExample <schemaFile> <xmlFile>"); 152 } 153 } 154
| Popular Tags
|