问题描述
我想将 SOAPBody 转换为字符串.最好的方法是什么?我应该先将其转换为 xml,然后将其转换为 String 还是我们可以将其转换为 String.
I want to convert SOAPBody to String. What is the best way to do it?Should i first convert it to xml and then convert it into String or we can jsut convert it into String.
推荐答案
当从 SOAPMessage 开始时,最简单的方法是使用 writeTo
方法:
When starting from a SOAPMessage, the easiest way is to use the writeTo
method :
ByteArrayOutputStream stream = new ByteArrayOutputStream();
soapMessage.writeTo(stream);
String message = new String(stream.toByteArray(), "utf-8")
(以上,我假设您的 SAAJ 实现将使用 UTF-8,您可能需要检查一下).
(Above, I assume your SAAJ implementation will use UTF-8, you'd probably want to check).
如果从 SOAPBody 开始,那么您可能应该使用 XML API,因为 SOAPBody 是一个 org.w3.dom.Element,最简单的方法可能是使用 TrAX :
If starting from a SOAPBody, then you probably should use XML APIs, seeing SOAPBody is a org.w3.dom.Element, the easiest way would probably be using TrAX :
SOAPBody element = ... // Whatever
DOMSource source = new DOMSource(element);
StringWriter stringResult = new StringWriter();
TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(stringResult));
String message = stringResult.toString();
(抱歉,我这里没有我的 IDE,无法检查它是否可以编译,但应该很接近).
(Sorry I do not have my IDE right here, can not check if this compiles, but that should be pretty close).
请注意:序列化的 SOAPMessage 可能不是原始 XML:它可能是 MIME 结构:如果 SOAPMessage 实际使用 SwA(带附件的 SOAP)或 MTOM.但是,SOAPBody 绝对是纯 XML.
Please note : A serialized SOAPMessage may not be raw XML : it might be a MIME structure : if the SOAPMessage actually uses SwA (SOAP With Attachment) or MTOM. However, SOAPBody is definitely pure XML.
这篇关于如何将 SOAPBody 转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!