Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
83 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...