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 XML4JDOMAdapter extends AbstractDOMAdapter { 75 76 private static final String CVS_ID = 77 "@(#) $RCSfile: XML4JDOMAdapter.java,v $ $Revision: 1.17 $ $Date: 2004/02/06 09:28:31 $ $Name: $"; 78 79 90 public Document getDocument(InputStream in, boolean validate) 91 throws IOException, JDOMException { 92 93 try { 94 98 99 Class parserClass = Class.forName("org.apache.xerces.parsers.DOMParser"); 101 Object parser = parserClass.newInstance(); 102 103 Method setFeature = 105 parserClass.getMethod("setFeature", 106 new Class [] {java.lang.String .class, 107 boolean.class}); 108 setFeature.invoke(parser, new Object [] {"http://xml.org/sax/features/validation", 109 new Boolean (validate)}); 110 111 setFeature.invoke(parser, new Object [] {"http://xml.org/sax/features/namespaces", 113 new Boolean (false)}); 114 115 if (validate) { 117 Method setErrorHandler = 118 parserClass.getMethod("setErrorHandler", 119 new Class [] {ErrorHandler.class}); 120 setErrorHandler.invoke(parser, new Object [] {new BuilderErrorHandler()}); 121 } 122 123 Method parse = 125 parserClass.getMethod("parse", 126 new Class [] {org.xml.sax.InputSource .class}); 127 parse.invoke(parser, new Object []{new InputSource(in)}); 128 129 Method getDocument = parserClass.getMethod("getDocument", null); 131 Document doc = (Document )getDocument.invoke(parser, null); 132 133 return doc; 134 } catch (InvocationTargetException e) { 135 Throwable targetException = e.getTargetException(); 136 if (targetException instanceof org.xml.sax.SAXParseException ) { 137 SAXParseException parseException = (SAXParseException)targetException; 138 throw new JDOMException("Error on line " + parseException.getLineNumber() + 139 " of XML document: " + parseException.getMessage(), parseException); 140 } else if (targetException instanceof IOException) { 141 IOException ioException = (IOException) targetException; 142 throw ioException; 143 } else { 144 throw new JDOMException(targetException.getMessage(), targetException); 145 } 146 } catch (Exception e) { 147 throw new JDOMException(e.getClass().getName() + ": " + 148 e.getMessage(), e); 149 } 150 } 151 152 159 public Document createDocument() throws JDOMException { 160 try { 161 return 162 (Document )Class.forName( 163 "org.apache.xerces.dom.DocumentImpl") 164 .newInstance(); 165 166 } catch (Exception e) { 167 throw new JDOMException(e.getClass().getName() + ": " + 168 e.getMessage() + " while creating document", e); 169 } 170 } 171 } 172 | Popular Tags |