예제 #1
0
  /**
   * Returns a transformer for the given XSLT file. If one already exists, it will be returned and
   * no new one will be created.
   *
   * @param xsltFileName the name of the XSLT file to use
   * @return The transformer that uses the given XSLT file or null, if none could be created.
   */
  private static Transformer getTransformer(String xsltFileName) {
    String key = xsltFileName + "-" + Thread.currentThread().getId();
    if (transformers.containsKey(key)) {
      return transformers.get(key);
    }
    InputStream xsltFile = XsltRunner.class.getResourceAsStream("/" + xsltFileName);
    if (xsltFile == null) {
      Log.error(TAG, "Error could not find: " + xsltFileName);
      return null;
    }
    try {
      Source xsltSource = new StreamSource(xsltFile);
      TransformerFactory transFactory = TransformerFactory.newInstance();

      // Add a URI resolver so that the XSL docs may import other XSL docs
      // using relative paths
      transFactory.setURIResolver(
          new URIResolver() {

            public Source resolve(String href, String base) throws TransformerException {
              InputStream is = XsltRunner.class.getResourceAsStream("/" + href);
              return new StreamSource(is);
            }
          });

      Transformer transformer = transFactory.newTransformer(xsltSource);
      transformers.put(key, transformer);
      return transformer;
    } catch (TransformerConfigurationException e) {
      Log.error(TAG, "Could not create transformer for " + xsltFileName + ": " + e.getMessage());
    }
    return null;
  }
예제 #2
0
  /**
   * Runs an XSLT file on the given JDOM document.
   *
   * @param xsltFileName The name of the file that contains the XSLT definition.
   * @param doc The JDOM document the XSL transformation should be applied to. The first index
   *     refers to the i-th parameter, the index will be 0 for the parameter name and 1 for the
   *     parameter value. See {@link Transformer#setParameter(String, Object)}
   * @param xsltParams Parameters that should be applied to the transformation.
   * @return The output file with the result of the transformation.
   */
  public static OutputFile runXSLT(String xsltFileName, Document doc, String[][] xsltParams) {
    StringWriter writer = new StringWriter();
    try {
      Transformer transformer = getTransformer(xsltFileName);
      transformer.reset();
      if (xsltParams != null) {
        for (int i = 0; i < xsltParams.length; i++)
          transformer.setParameter(xsltParams[i][0], xsltParams[i][1]);
      }
      DocumentWrapper docw =
          new DocumentWrapper(doc, "", ((Controller) transformer).getConfiguration());
      Result result = new StreamResult(writer);
      transformer.transform(docw, result);

      return new OutputFile(writer.toString());
    } catch (TransformerException e) {
      Log.error(TAG, e.getMessage());
    }
    return null;
  }