1 7 8 package org.dom4j.io; 9 10 import java.io.IOException ; 11 12 import org.dom4j.Document; 13 14 import org.xml.sax.ContentHandler ; 15 import org.xml.sax.ErrorHandler ; 16 import org.xml.sax.SAXException ; 17 import org.xml.sax.XMLReader ; 18 import org.xml.sax.helpers.DefaultHandler ; 19 20 32 public class SAXValidator { 33 34 private XMLReader xmlReader; 35 36 37 private ErrorHandler errorHandler; 38 39 public SAXValidator() { 40 } 41 42 public SAXValidator(XMLReader xmlReader) { 43 this.xmlReader = xmlReader; 44 } 45 46 58 public void validate(Document document) throws SAXException { 59 if (document != null) { 60 XMLReader reader = getXMLReader(); 61 62 if (errorHandler != null) { 63 reader.setErrorHandler(errorHandler); 64 } 65 66 try { 67 reader.parse(new DocumentInputSource(document)); 68 } catch (IOException e) { 69 throw new RuntimeException ("Caught and exception that should " 70 + "never happen: " + e); 71 } 72 } 73 } 74 75 78 86 public XMLReader getXMLReader() throws SAXException { 87 if (xmlReader == null) { 88 xmlReader = createXMLReader(); 89 configureReader(); 90 } 91 92 return xmlReader; 93 } 94 95 104 public void setXMLReader(XMLReader reader) throws SAXException { 105 this.xmlReader = reader; 106 configureReader(); 107 } 108 109 114 public ErrorHandler getErrorHandler() { 115 return errorHandler; 116 } 117 118 125 public void setErrorHandler(ErrorHandler errorHandler) { 126 this.errorHandler = errorHandler; 127 } 128 129 132 141 protected XMLReader createXMLReader() throws SAXException { 142 return SAXHelper.createXMLReader(true); 143 } 144 145 151 protected void configureReader() throws SAXException { 152 ContentHandler handler = xmlReader.getContentHandler(); 153 154 if (handler == null) { 155 xmlReader.setContentHandler(new DefaultHandler ()); 156 } 157 158 xmlReader.setFeature("http://xml.org/sax/features/validation", true); 160 161 xmlReader.setFeature("http://xml.org/sax/features/namespaces", true); 163 xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", 164 false); 165 } 166 } 167 168 204 | Popular Tags |