1 32 33 package com.knowgate.dataxslt; 34 35 import java.io.*; 36 37 import org.xml.sax.ContentHandler ; 38 import org.xml.sax.ErrorHandler ; 39 import org.xml.sax.helpers.DefaultHandler ; 40 import org.xml.sax.helpers.XMLReaderFactory ; 41 import org.xml.sax.InputSource ; 42 import org.xml.sax.SAXException ; 43 import org.xml.sax.SAXParseException ; 44 import org.xml.sax.XMLReader ; 45 46 52 53 public class SAXValidate extends DefaultHandler 54 implements ErrorHandler { 55 56 private static final String 57 DEFAULT_PARSER = "org.apache.xerces.parsers.SAXParser"; 58 private boolean schemavalidate = false; 59 60 63 public SAXValidate(boolean validateschema) { 64 this.schemavalidate = validateschema; 65 } 66 67 public void error (SAXParseException exception) throws SAXException { 68 System.out.println("ERROR: " + exception.getMessage()); 69 } 70 71 74 static public void main(String [] args) { 75 76 if (args.length < 1 || args.length > 2) { 77 System.err.println("USO: java SAXValidate [-s] <xmlfile>"); 78 } else { 79 boolean svalidate = false; 80 String filename = ""; 81 82 if (args.length > 1) { 83 if (args[0].equals("-s")) { 84 svalidate = true; 85 } 86 filename = args[1]; 87 } else { 88 filename = args[0]; 89 } 90 91 SAXValidate test = new SAXValidate(svalidate); 92 93 try { 94 test.runTest(new FileReader(new File(filename).toString()), 95 DEFAULT_PARSER); 96 } catch (Exception e) { 97 System.err.println("Error running test."); 98 System.err.println(e.getMessage()); 99 e.printStackTrace(System.err); 100 } 101 } 102 } 103 104 110 111 public void runTest(Reader xml, String parserName) 112 throws IOException, ClassNotFoundException { 113 114 try { 115 116 XMLReader parser = XMLReaderFactory.createXMLReader(parserName); 118 119 parser.setContentHandler((ContentHandler )this); 121 parser.setErrorHandler((ErrorHandler )this); 122 123 parser.setFeature("http://xml.org/sax/features/validation", true); 124 if (schemavalidate) { 125 parser.setFeature("http://apache.org/xml/features/validation/schema", true); 126 } 127 128 parser.parse(new InputSource (xml)); 130 131 } catch (SAXParseException e) { 132 System.err.println(e.getMessage()); 133 } catch (SAXException e) { 134 System.err.println(e.getMessage()); 135 } catch (Exception e) { 136 System.err.println(e.toString()); 137 } 138 } 139 } 140 | Popular Tags |