Transformer: transform(Source xmlSource, Result outputTarget)

I am new to javax.xml.transform ยป Transformer What I am trying to achieve is that, I am applying an XSLT on a XML document. It works. What I want to achieve is to be able to write the Output to an OutputStream.

This is my code:

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

I know that I can use it to write to a file like this, but I want to write it to a OutputStream Object.

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

The Result outputTarget of transform(Source xmlSource, Result outputTarget), Can someone guide me how to pass an OutputStream to be used and how to pass it.

Thank you very much.

This is the error I am getting when I am passing the outputstream:

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


Use a StreamResult. It provides constructors to write to a File or an OutputStream:

Example using File:

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

Example using FileOutputStream:

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

Example using ByteArrayOutputStream:

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

Need Your Help

If statement seems to skip though requirements are met

java string if-statement equals

I have a very simple question that I really can't understand.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.