将StreamResult转换为字符串或xml


问题内容

使用spring ws获取StreamResult如下

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

我得到了结果,但是我想将其提取到某种xml甚至是字符串中(只是想查看内容以便生成响应)。

我怎样才能做到这一点?


问题答案:

试试这个:

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