1 9 10 package org.dom4j.samples.validate; 11 12 import org.dom4j.samples.AbstractDemo; 13 14 import org.dom4j.Document; 15 import org.dom4j.DocumentException; 16 import org.dom4j.DocumentType; 17 import org.dom4j.Element; 18 import org.dom4j.io.OutputFormat; 19 import org.dom4j.io.SAXReader; 20 import org.dom4j.io.SAXValidator; 21 import org.dom4j.io.XMLWriter; 22 import org.dom4j.util.XMLErrorHandler; 23 import org.xml.sax.SAXException ; 24 25 31 public class SAXValidatorDemo extends AbstractDemo { 32 33 public static void main(String [] args) { 34 run(new SAXValidatorDemo(), args); 35 } 36 37 public SAXValidatorDemo() { 38 } 39 40 public void run(String [] args) throws Exception { 41 if (args.length < 1) { 42 printUsage("<xmlFileNameOrURL> <onParse>"); 43 } 44 45 String fileName = args[0]; 46 boolean validateOnParse = false; 47 if (args.length > 1) { 48 String boolText = args[1]; 49 if (boolText.equalsIgnoreCase("true")) { 50 validateOnParse = true; 51 } 52 } 53 54 validate(fileName, validateOnParse); 55 } 56 57 protected void validate(String url, boolean validateOnParse) 58 throws Exception { 59 println("Parsing: " + url + " with validation mode: " + validateOnParse); 60 61 XMLErrorHandler errorHandler = new XMLErrorHandler(); 62 63 if (validateOnParse) { 64 SAXReader reader = new SAXReader(true); 66 reader.setErrorHandler(errorHandler); 67 68 try { 69 Document document = reader.read(url); 70 println("Document: " + url + " is valid!"); 71 } catch (DocumentException e) { 72 println("Document: " + url + " is not valid"); 73 println("Exception: " + e); 74 } 75 } else { 76 SAXReader reader = new SAXReader(); 78 Document document = reader.read(url); 79 80 println("Document URI: " + document.getName()); 81 82 DocumentType docType = document.getDocType(); 84 if (docType == null) { 85 println("Adding an NITF doc type"); 86 document.addDocType("nitf", null, "nitf.dtd"); 87 } 88 89 try { 91 SAXValidator validator = new SAXValidator(); 92 validator.setErrorHandler(errorHandler); 93 validator.validate(document); 94 95 println("Document: " + url + " is valid!"); 96 } catch (SAXException e) { 97 println("Document: " + url + " is not valid"); 98 println("Exception: " + e); 99 } 100 } 101 102 Element errors = errorHandler.getErrors(); 104 if (errors.hasContent()) { 105 XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); 106 writer.write(errors); 107 } 108 } 109 } 110 111 149 | Popular Tags |