1 package org.hibernate.util; 3 4 import java.util.List ; 5 6 import org.apache.commons.logging.Log; 7 import org.apache.commons.logging.LogFactory; 8 import org.dom4j.io.DOMReader; 9 import org.dom4j.io.SAXReader; 10 import org.dom4j.Element; 11 import org.dom4j.DocumentFactory; 12 import org.xml.sax.EntityResolver ; 13 import org.xml.sax.ErrorHandler ; 14 import org.xml.sax.SAXParseException ; 15 16 22 public final class XMLHelper { 23 24 private static final Log log = LogFactory.getLog(XMLHelper.class); 25 public static final EntityResolver DEFAULT_DTD_RESOLVER = new DTDEntityResolver(); 26 27 private DOMReader domReader; 28 private SAXReader saxReader; 29 30 34 public SAXReader createSAXReader(String file, List errorsList, EntityResolver entityResolver) { 35 if (saxReader==null) saxReader = new SAXReader(); 36 saxReader.setEntityResolver(entityResolver); 37 saxReader.setErrorHandler( new ErrorLogger(file, errorsList) ); 38 saxReader.setMergeAdjacentText(true); 39 saxReader.setValidation(true); 40 return saxReader; 41 } 42 43 46 public DOMReader createDOMReader() { 47 if (domReader==null) domReader = new DOMReader(); 48 return domReader; 49 } 50 51 public static class ErrorLogger implements ErrorHandler { 52 private String file; 53 private List errors; 54 ErrorLogger(String file, List errors) { 55 this.file=file; 56 this.errors = errors; 57 } 58 public void error(SAXParseException error) { 59 log.error( "Error parsing XML: " + file + '(' + error.getLineNumber() + ") " + error.getMessage() ); 60 errors.add(error); 61 } 62 public void fatalError(SAXParseException error) { 63 error(error); 64 } 65 public void warning(SAXParseException warn) { 66 log.warn( "Warning parsing XML: " + file + '(' + warn.getLineNumber() + ") " + warn.getMessage() ); 67 } 68 } 69 70 public static Element generateDom4jElement(String elementName) { 71 return DocumentFactory.getInstance().createElement( elementName ); 72 } 73 } 74 75 76 77 78 79 80 | Popular Tags |