예제 #1
0
파일: XMLUtil.java 프로젝트: Zoramite/railo
  /**
   * parse XML/HTML String to a XML DOM representation
   *
   * @param xml XML InputSource
   * @param isHtml is a HTML or XML Object
   * @return parsed Document
   * @throws SAXException
   * @throws IOException
   * @throws ParserConfigurationException
   */
  public static final Document parse(InputSource xml, InputSource validator, boolean isHtml)
      throws SAXException, IOException {

    if (!isHtml) {
      // try to load org.apache.xerces.jaxp.DocumentBuilderFactoryImpl, oracle impl sucks
      DocumentBuilderFactory factory = null;
      try {
        factory = new DocumentBuilderFactoryImpl();
      } catch (Throwable t) {
        factory = DocumentBuilderFactory.newInstance();
      }

      // print.o(factory);
      if (validator == null) {
        XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_EXTERNAL, Boolean.FALSE);
        XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_GRAMMAR, Boolean.FALSE);
      } else {
        XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA, Boolean.TRUE);
        XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA_FULL_CHECKING, Boolean.TRUE);
      }

      factory.setNamespaceAware(true);
      factory.setValidating(validator != null);

      try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new XMLEntityResolverDefaultHandler(validator));
        builder.setErrorHandler(new ThrowingErrorHandler(true, true, false));
        return builder.parse(xml);
      } catch (ParserConfigurationException e) {
        throw new SAXException(e);
      }

      /*DOMParser parser = new DOMParser();
      print.out("parse");
      parser.setEntityResolver(new XMLEntityResolverDefaultHandler(validator));
      parser.parse(xml);
      return parser.getDocument();*/
    }

    XMLReader reader = new Parser();
    reader.setFeature(Parser.namespacesFeature, true);
    reader.setFeature(Parser.namespacePrefixesFeature, true);

    try {
      Transformer transformer = TransformerFactory.newInstance().newTransformer();

      DOMResult result = new DOMResult();
      transformer.transform(new SAXSource(reader, xml), result);
      return XMLUtil.getDocument(result.getNode());
    } catch (Exception e) {
      throw new SAXException(e);
    }
  }