Java Transformer: How do you render your result in an OutputStream?

I am new to javax.xml.transform.Transformer


I am applying XSLT

in doc XML

and it works great.

What I want to achieve is to write the output of this transformation into OutputStream


This is my code:

OutputStream outputStream = null;
InputStream agent = new FileInputStream("src/res/testxmlfile.xml");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource("src/res/trans.xslt"));
transformer.transform(new StreamSource(agent), outputStream ????????);


I know it can be used to write such a file, but I want to write it to OutputStream


transformer.transform(new StreamSource(agent),
                      new StreamResult(new FileOutputStream("/result.xml")));


How to pass OutputStream

to be used here?

This is the error I get when I pass OutputStream


Exception in thread "main" javax.xml.transform.TransformerException:
                            Result object passed to ''{0}'' is invalid.
at com.gohealth.TestXmlStream.main(



source to share

2 answers

Use StreamResult

. It provides constructors to write to File

or OutputStream


Usage example File


transformer.transform(new StreamSource(agent), new StreamResult(file));


Usage example FileOutputStream


FileOutputStream outputStream = new FileOutputStream(new File("outputfile.xml"));
transformer.transform(new StreamSource(agent), new StreamResult(outputStream));


Usage example ByteArrayOutputStream


ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
transformer.transform(new StreamSource(agent), new StreamResult(outputStream));
byte[] bytes = outputStream.toByteArray();`




Use a "StreamResult" built with an object that represents where you want to get. See



All Articles