import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.OutputStreamWriter;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import com.ibatis.common.exception.NestedRuntimeException;
Document getDoc(Reader reader) {
try {
// Configuration
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);
dbf.setValidating(true);
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setCoalescing(false);
dbf.setExpandEntityReferences(false);
OutputStreamWriter errorWriter = new OutputStreamWriter(System.err);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new SimpleErrorHandler(new PrintWriter(errorWriter, true)));
//db.setEntityResolver(new DaoClasspathEntityResolver());
// Parse input file
Document doc = db.parse(new ReaderInputStream(reader));
return doc;
} catch (Exception e) {
throw new NestedRuntimeException("XML Parser Error. Cause: " + e);
}
}
/**********************************************************/
private static class SimpleErrorHandler implements ErrorHandler {
/**
* Error handler output goes here
*/
private PrintWriter out;
SimpleErrorHandler(PrintWriter out) {
this.out = out;
}
/**
* Returns a string describing parse exception details
*/
private String getParseExceptionInfo(SAXParseException spe) {
String systemId = spe.getSystemId();
if (systemId == null) {
systemId = "null";
}
String info = "URI=" + systemId +
" Line=" + spe.getLineNumber() +
": " + spe.getMessage();
return info;
}
// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.
public void warning(SAXParseException spe) throws SAXException {
out.println("Warning: " + getParseExceptionInfo(spe));
}
public void error(SAXParseException spe) throws SAXException {
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
public void fatalError(SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
}