ivaneeo's blog

自由的力量,自由的生活。

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  669 Posts :: 0 Stories :: 64 Comments :: 0 Trackbacks
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);
    }
  }

posted on 2005-08-08 10:12 ivaneeo 阅读(301) 评论(0)  编辑  收藏 所属分类: java魔力

只有注册用户登录后才能发表评论。


网站导航: