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

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

java - How to convert SOAPBody to 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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") 

(Above, I assume your SAAJ implementation will use UTF-8, you'd probably want to check).

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

(Sorry I do not have my IDE right here, can not check if this compiles, but that should be pretty close).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...