import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;
import java.io.StringWriter;
public class XsltTransformer {
public static String transformer(InputStream xml, InputStream xslt) throws TransformerException {
Source xmlSource = new StreamSource(xml);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory transFact = TransformerFactory.newInstance();
Source xsltSource = new StreamSource(xslt);
Transformer trans = transFact.newTransformer(xsltSource);
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
trans.transform(xmlSource, result);
return stringWriter.getBuffer().toString();
}
}
Secondly, combined with XMLUnit, Junit to verify
@Test
public void testXSLT() {
InputStream expectedOutput = ODSEventXsltTest.class.getResourceAsStream("ods-output.xml");
InputStream xml = ODSEventXsltTest.class.getResourceAsStream("ods.xml");
InputStream xslt = ODSEventXsltTest.class.getResourceAsStream("SSNOdsExportToCannonical.xsl");
try {
String actual = XsltTransformer.transformer(xml, xslt);
String expected = IOUtils.toString(expectedOutput);
XMLUnit.setIgnoreWhitespace(true);
Diff diff = XMLUnit.compareXML(expected, actual);
String errorMessage = "\nexpected:\n" + expected + "\n-------------------------------------\nbut actual: \n" + actual + "\n>>>>" + diff.toString();
assertTrue(errorMessage, diff.similar());
} catch (TransformerException e) {
fail(e.getLocalizedMessage());
} catch (SAXException e) {
fail(e.getLocalizedMessage());
} catch (IOException e) {
fail(e.getLocalizedMessage());
}
}