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

Object.

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.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
                           .getOutputHandler(TransformerImpl.java:468)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
                           .transform(TransformerImpl.java:344)
at com.gohealth.TestXmlStream.main(TestXmlStream.java:75)

      

+3


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();`

      

+3


source


Use a "StreamResult" built with an object that represents where you want to get. See http://docs.oracle.com/javase/7/docs/api/javax/xml/transform/stream/StreamResult.html



+2


source







All Articles