1 package org.opensrf.util;
2 import javax.xml.transform.*;
3 import javax.xml.transform.stream.*;
4 import javax.xml.parsers.*;
6 import java.io.ByteArrayInputStream;
7 import java.io.OutputStream;
8 import java.io.ByteArrayOutputStream;
12 * Performs XSL transformations.
13 * TODO: Add ability to pass in XSL variables
15 public class XMLTransformer {
17 /** The XML to transform */
18 private Source xmlSource;
19 /** The stylesheet to apply */
20 private Source xslSource;
22 public XMLTransformer(Source xmlSource, Source xslSource) {
23 this.xmlSource = xmlSource;
24 this.xslSource = xslSource;
27 public XMLTransformer(String xmlString, File xslFile) {
29 new StreamSource(new ByteArrayInputStream(xmlString.getBytes())),
30 new StreamSource(xslFile));
33 public XMLTransformer(File xmlFile, File xslFile) {
35 new StreamSource(xmlFile),
36 new StreamSource(xslFile));
40 * Applies the transformation and puts the result into the provided output stream
42 public void apply(OutputStream outStream) throws TransformerException, TransformerConfigurationException {
43 Result result = new StreamResult(outStream);
44 Transformer trans = TransformerFactory.newInstance().newTransformer(xslSource);
45 trans.transform(xmlSource, result);
49 * Applies the transformation and return the resulting string
50 * @return The String created by the XSL transformation
52 public String apply() throws TransformerException, TransformerConfigurationException {
53 OutputStream outStream = new ByteArrayOutputStream();
54 this.apply(outStream);
55 return outStream.toString();