Pretty printing SOAP messages

If your dealing with SAAJ API or you want to create a Debug Message Handler that prints the SOAP Message then you can call SOAPmessage.writeTo(System.out), but this method writes the full SOAP message in one line and which can be little hard to read this is sample output

<SOAP-ENV:Envelope xmlns:SOAP-ENV=""><SOAP-ENV:Body><wn:sayHello SOAP-ENV:encodingStyle="" xmlns:wn=""><arg0>Sunil</arg0></wn:sayHello></SOAP-ENV:Body></SOAP-ENV:Envelope>

If you want to pretty print the SOAPMessage then you can use the following method.


import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
public class SOAPHelper {
public static String getSOAPMessageAsString(SOAPMessage soapMessage) {
try {

TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();

// Set formatting

tf.setOutputProperty(OutputKeys.INDENT, "yes");

Source sc = soapMessage.getSOAPPart().getContent();

ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
StreamResult result = new StreamResult(streamOut);
tf.transform(sc, result);

String strMessage = streamOut.toString();
return strMessage;
} catch (Exception e) {
System.out.println("Exception in getSOAPMessageAsString "
+ e.getMessage());
return null;


It generates the output which looks like this

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="">
<wn:sayHello SOAP-ENV:encodingStyle="" xmlns:wn="">

I ended up doing this because i could not find class


Anonymous said...

Thanks, that's useful!

Anonymous said...

good one

Muhammad Alpinthor Muthahari said...

very useful, thanks!

Anonymous said...

this worked perfectly, thank you

Anonymous said...

Worked. Awesome post!!!

Anonymous said...

Perfect, thanks!