Exemple #1
0
  static {
    DocumentBuilderFactory factory = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
    try {
      builder = factory.newDocumentBuilder();
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      // Create an instance of our own transformer factory impl
      TransformerFactory transFactory =
          new com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl();

      // create Transformer
      transformer = transFactory.newTransformer();

    } catch (TransformerConfigurationException tce) {
      // Error generated by the parser
      System.out.println("* Transformer Factory error");
      System.out.println("  " + tce.getMessage());

      // Use the contained exception, if any
      Throwable x = tce;
      if (tce.getException() != null) x = tce.getException();
      x.printStackTrace();
    }
  }
  private String formatXML(String str) {
    try {
      // Use a Transformer for output
      TransformerFactory tFactory = TransformerFactory.newInstance();
      // Surround this setting in a try/catch for compatibility with Java 1.4. This setting is
      // required
      // for Java 1.5
      try {
        tFactory.setAttribute("indent-number", 2);
      } catch (IllegalArgumentException e) {
        // Ignore
      }
      Transformer transformer = tFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      // Transform the requested string into a nice formatted XML string
      StreamSource source = new StreamSource(new StringReader(str));
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);
      transformer.transform(source, result);
      return sw.toString();

    } catch (TransformerConfigurationException tce) {
      // Error generated by the parser
      System.out.println("\n** Transformer Factory error");
      System.out.println("   " + tce.getMessage());

      // Use the contained exception, if any
      Throwable x = tce;
      if (tce.getException() != null) x = tce.getException();
      x.printStackTrace();

    } catch (TransformerException te) {
      // Error generated by the parser
      System.out.println("\n** Transformation error");
      System.out.println("   " + te.getMessage());

      // Use the contained exception, if any
      Throwable x = te;
      if (te.getException() != null) x = te.getException();
      x.printStackTrace();
    }
    return str;
  }