1 56 57 package org.jdom.adapters; 58 59 import java.io.*; 60 import java.lang.reflect.*; 61 62 import org.jdom.*; 63 import org.jdom.input.*; 64 import org.w3c.dom.Document ; 65 import org.xml.sax.*; 66 67 74 public class XercesDOMAdapter extends AbstractDOMAdapter { 75 76 private static final String CVS_ID = 77 "@(#) $RCSfile: XercesDOMAdapter.java,v $ $Revision: 1.18 $ $Date: 2004/02/06 09:28:31 $ $Name: $"; 78 79 91 public Document getDocument(InputStream in, boolean validate) 92 throws IOException, JDOMException { 93 94 try { 95 Class parserClass = 97 Class.forName("org.apache.xerces.parsers.DOMParser"); 98 Object parser = parserClass.newInstance(); 99 100 Method setFeature = parserClass.getMethod( 102 "setFeature", 103 new Class [] {java.lang.String .class, boolean.class}); 104 setFeature.invoke(parser, 105 new Object [] {"http://xml.org/sax/features/validation", 106 new Boolean (validate)}); 107 108 setFeature.invoke(parser, 110 new Object [] {"http://xml.org/sax/features/namespaces", 111 new Boolean (true)}); 112 113 if (validate) { 115 Method setErrorHandler = parserClass.getMethod( 116 "setErrorHandler", 117 new Class [] {ErrorHandler.class}); 118 setErrorHandler.invoke(parser, 119 new Object [] {new BuilderErrorHandler()}); 120 } 121 122 Method parse = parserClass.getMethod( 124 "parse", 125 new Class [] {org.xml.sax.InputSource .class}); 126 parse.invoke(parser, new Object []{new InputSource(in)}); 127 128 Method getDocument = parserClass.getMethod("getDocument", null); 130 Document doc = (Document )getDocument.invoke(parser, null); 131 132 return doc; 133 } catch (InvocationTargetException e) { 134 Throwable targetException = e.getTargetException(); 135 if (targetException instanceof org.xml.sax.SAXParseException ) { 136 SAXParseException parseException = 137 (SAXParseException)targetException; 138 throw new JDOMException("Error on line " + 139 parseException.getLineNumber() + 140 " of XML document: " + 141 parseException.getMessage(), e); 142 } else if (targetException instanceof IOException) { 143 IOException ioException = (IOException) targetException; 144 throw ioException; 145 } else { 146 throw new JDOMException(targetException.getMessage(), e); 147 } 148 } catch (Exception e) { 149 throw new JDOMException(e.getClass().getName() + ": " + 150 e.getMessage(), e); 151 } 152 } 153 154 161 public Document createDocument() throws JDOMException { 162 try { 163 return (Document )Class.forName( 164 "org.apache.xerces.dom.DocumentImpl").newInstance(); 165 } catch (Exception e) { 166 throw new JDOMException(e.getClass().getName() + ": " + 167 e.getMessage() + " when creating document", e); 168 } 169 } 170 } 171
| Popular Tags
|