Convert StreamResult to string or xml

user1609085 picture user1609085 · Apr 22, 2014 · Viewed 41.5k times · Source

Using spring ws to get the StreamResult as below

StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult("http://someUri", 
                source, new SoapActionCallback("someCallBack"), result); 
return result;

I get the result, But I want to extract it to some sort of xml or even as a string (Just want to see the contents in order to generate the response).

How can I do this?

Answer

Asif Bhutto picture Asif Bhutto · Apr 22, 2014

Try this one:

try {
    StreamSource source = new StreamSource(new StringReader("<xml>blabla</xml>"));
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.transform(source,result);
    String strResult = writer.toString();
} catch (Exception e) {
    e.printStackTrace();
}