Akshay Bijawe Akshay Bijawe - 5 months ago 5x
Java Question

Saxon implementation for Stream of data

In my code below, I’m modifying the XML file with XSLT using SAXON

import java.io.File;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class SaxonImplementation {

public static void simpleTransform(String sourcePath, String xsltPath,
String resultDir) {
TransformerFactory tFactory = TransformerFactory.newInstance();
try {
Transformer transformer = tFactory
.newTransformer(new StreamSource(new File(xsltPath)));
transformer.transform(new StreamSource(new File(sourcePath)),
new StreamResult(new File(resultDir)));
} catch (Exception e) {

public static void main(String[] args) {
simpleTransform("first.xml", "newxsl.xslt", "second.xml");

Now instead of modifying the XML file, I want to modify an XML string. How shall I proceed here?
The transformer.transform method requires an XML source file and the result file. How can I provide an XML string instead of a file and get the results in the form of Stream?


You can create a StreamSource for a java.io.Reader therefore wrap the XML string in a StringReader and then in a StreamSource and pass that to the transformer:

String xml = ...
transformer.transform(new StreamSource(new StringReader(xml)), ...

Same is true for the StreamResult, you can use any OutputStream or Writer to create a StreamResult.

And this works for any Trax implementation not just for Saxon.