24

I want to convert the stream result output to string since I want to use it in Junit I think that I need to use the string writer but Im not sure how exactly to use it.

StreamResult result = new StreamResult(new File("C:\\file.xml"));
transformer.transform(source, result);

Thanks Fedor

3 Answers 3

39

Have a look at and learn to use the javadocs of the StreamResult class (http://java.sun.com/javase/6/docs/api/). One of the constructors of StreamResult takes a Writer object as a parameter. You will see that one of the sub-classes of Writer is StringWriter. So to obtain a string from what is written to the StreamResult, you can construct a StringWriter, put it into the StreamResult, transform() the Source to the StreamResult and get the string from the StringWriter.

//create a StringWriter for the output
StringWriter outWriter = new StringWriter();
StreamResult result = new StreamResult( outWriter );
...
transformer.transform( source, result );  
StringBuffer sb = outWriter.getBuffer(); 
String finalstring = sb.toString();
4
  • Hello Timo,Thanks but where should I put the converter StreamResult result = new StreamResult(new File("C:\\file.xml"));
    – user1578363
    Nov 4, 2012 at 11:05
  • Well, you either put the result into a file using StreamResult result = new StreamResult(new File("C:\\file.xml")); or you put it into a StringWriter using StreamResult result = new StreamResult( outWriter ); Why using a file if you want it in a string?
    – Timo Hahn
    Nov 4, 2012 at 11:11
  • what is 'source' representing? Feb 15, 2015 at 0:07
  • I'd guess that source is the XML that is getting transformed. Jul 10, 2015 at 17:13
32
StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
String output = writer.toString();
0
3

You can use a StringWriter in this way :

StringWriter sw = (StringWriter) result.getWriter(); 
StringBuffer sb = sw.getBuffer(); 
String finalstring = sb.toString();
2
  • this is the one i was looking for
    – divine
    Jun 13, 2016 at 8:13
  • What is the difference between using a buffer or not, like in @nosid answer? Apr 5, 2017 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.