KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > util > XMLHelper


1 //$Id: XMLHelper.java,v 1.3 2005/02/12 07:19:50 steveebersole Exp $
2
package org.hibernate.util;
3
4 import java.util.List JavaDoc;
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 JavaDoc;
13 import org.xml.sax.ErrorHandler JavaDoc;
14 import org.xml.sax.SAXParseException JavaDoc;
15
16 /**
17  * Small helper class that lazy loads DOM and SAX reader and keep them for fast use afterwards.
18  *
19  *
20  *
21  */

22 public final class XMLHelper {
23
24     private static final Log log = LogFactory.getLog(XMLHelper.class);
25     public static final EntityResolver JavaDoc DEFAULT_DTD_RESOLVER = new DTDEntityResolver();
26
27     private DOMReader domReader;
28     private SAXReader saxReader;
29
30     /**
31      * Create a dom4j SAXReader which will append all validation errors
32      * to errorList
33      */

34     public SAXReader createSAXReader(String JavaDoc file, List JavaDoc errorsList, EntityResolver JavaDoc 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     /**
44      * Create a dom4j DOMReader
45      */

46     public DOMReader createDOMReader() {
47         if (domReader==null) domReader = new DOMReader();
48         return domReader;
49     }
50
51     public static class ErrorLogger implements ErrorHandler JavaDoc {
52         private String JavaDoc file;
53         private List JavaDoc errors;
54         ErrorLogger(String JavaDoc file, List JavaDoc errors) {
55             this.file=file;
56             this.errors = errors;
57         }
58         public void error(SAXParseException JavaDoc error) {
59             log.error( "Error parsing XML: " + file + '(' + error.getLineNumber() + ") " + error.getMessage() );
60             errors.add(error);
61         }
62         public void fatalError(SAXParseException JavaDoc error) {
63             error(error);
64         }
65         public void warning(SAXParseException JavaDoc warn) {
66             log.warn( "Warning parsing XML: " + file + '(' + warn.getLineNumber() + ") " + warn.getMessage() );
67         }
68     }
69
70     public static Element generateDom4jElement(String JavaDoc elementName) {
71         return DocumentFactory.getInstance().createElement( elementName );
72     }
73 }
74
75
76
77
78
79
80
Popular Tags