将流结果转换为字符串或 xml

2022-09-01 06:39:27

使用弹簧 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甚至字符串中(只想查看内容以生成响应)。

我该怎么做?


答案 1

试试这个:

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

答案 2

您可以使用 getReader() 获取 StreamSource 的读取器。然后,您应该能够使用read(char[] cbuf)将流的内容写入字符数组,如果您愿意,该字符数组可以轻松转换为字符串并打印到控制台。


推荐