1 9 10 package org.dom4j.samples.validate; 11 12 import org.dom4j.Document; 13 import org.dom4j.DocumentException; 14 import org.dom4j.io.SAXReader; 15 import org.dom4j.io.SAXWriter; 16 import org.iso_relax.verifier.Schema; 17 import org.iso_relax.verifier.Verifier; 18 import org.iso_relax.verifier.VerifierFactory; 19 import org.iso_relax.verifier.VerifierHandler; 20 import org.xml.sax.ErrorHandler ; 21 import org.xml.sax.SAXParseException ; 22 23 30 public class JARVDemo { 31 32 public static void main(String [] args) { 33 new JARVDemo().run(args); 34 } 35 36 public void run(String [] args) { 37 try { 38 if (args.length < 2) { 39 System.out.println("usage: <xmlDoc> <schemaDoc>"); 40 System.out 41 .println("Which validates the given XML document against the given schema document"); 42 System.out 43 .println("The schema can be XML Schema, RelaxNG, Relax or TREX"); 44 return; 45 } 46 String xmlFile = args[0]; 47 String schema = args[1]; 48 49 SAXReader reader = new SAXReader(); 50 Document document = reader.read(xmlFile); 51 process(document, schema); 52 } catch (DocumentException e) { 53 System.out.println("Exception occurred: " + e); 54 Throwable nestedException = e.getNestedException(); 55 if (nestedException != null) { 56 System.out.println("NestedException: " + nestedException); 57 nestedException.printStackTrace(); 58 } else { 59 e.printStackTrace(); 60 } 61 } catch (Throwable t) { 62 System.out.println("Exception occurred: " + t); 63 t.printStackTrace(); 64 } 65 } 66 67 68 protected void process(Document document, String schemaURI) 69 throws Exception { 70 71 System.out.println("Loaded schema document: " + schemaURI); 72 73 VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); 75 Schema schema = factory.compileSchema(schemaURI); 76 77 Verifier verifier = schema.newVerifier(); 78 verifier.setErrorHandler(new ErrorHandler () { 79 public void error(SAXParseException e) { 80 System.out.println("ERROR: " + e); 81 } 82 83 public void fatalError(SAXParseException e) { 84 System.out.println("FATAL: " + e); 85 } 86 87 public void warning(SAXParseException e) { 88 System.out.println("WARNING: " + e); 89 } 90 }); 91 92 System.out.println("Validating XML document"); 93 94 VerifierHandler handler = verifier.getVerifierHandler(); 95 SAXWriter writer = new SAXWriter(handler); 96 writer.write(document); 97 } 98 } 99 100 138 | Popular Tags |