I'd like to perform chained XML processing with several XSLT transformers in Java. The first transformer takes the input as a javax.xml.transform.Source and produces a javax.xml.transform.Result. Now I'd like to use the result as the input for the next transformation. I.e. I need the source for the second transformation.
How is it possible to create a Source from a Result (if it's possible at all)? Or is there some other solution for what I'd like to do?
One way is to set up the second transformation as a Sax TransformerHandler being the ContentHandler of the SAXResult of the first Transformer e.g.:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
String xslt1 = "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'><xsl:template match='/'><xsl:call-template name='identity'/><xsl:comment>sheet 1</xsl:comment></xsl:template><xsl:template name='identity' match='@* | node()'><xsl:copy><xsl:apply-templates select='@* | node()'/></xsl:copy></xsl:template></xsl:stylesheet>";
String xslt2 = "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'><xsl:template match='/'><xsl:call-template name='identity'/><xsl:comment>sheet 2</xsl:comment></xsl:template><xsl:template name='identity' match='@* | node()'><xsl:copy><xsl:apply-templates select='@* | node()'/></xsl:copy></xsl:template></xsl:stylesheet>";
Transformer transformer1 = transformerFactory.newTransformer(new StreamSource(new StringReader(xslt1)));
TransformerHandler transformer2 = ((SAXTransformerFactory)transformerFactory).newTransformerHandler(new StreamSource(new StringReader(xslt2)));
transformer2.setResult(new StreamResult(System.out));
transformer1.transform(new StreamSource(new StringReader("<root><item>a</item><item>b</item></root>")), new SAXResult(transformer2));
Or you can chain XSLT transformations as SAX XMLFilters: https://saxonica.plan.io/projects/saxon/repository/he/revisions/master/entry/latest10/samples/java/he/JAXPExamples.java#L694