Let's get started with a Microservice Architecture with Spring Cloud:
How to Get Raw XML From a SOAP Message in Java
Last updated: March 3, 2026
1. Introduction
When working with SOAP-based web services in Java, there are situations where accessing the raw XML of a SOAP message becomes necessary. We may need it for debugging integration issues, logging requests and responses for auditing, validating message structure, or troubleshooting interoperability problems between systems.
Although SOAP frameworks hide most XML processing from us, real-world projects often require visibility into the actual SOAP envelope that is being exchanged. The approach we use depends on the SOAP stack in our application, such as SAAJ, JAX-WS, Apache CXF, or Spring Web Services.
In this article, we’ll explore the most practical ways to retrieve raw XML from SOAP messages in Java. We’ll examine different frameworks, explain when to use each method, and highlight important considerations to avoid common pitfalls.
2. What Do We Mean by Raw XML
Before implementing any solution, we should clarify what raw XML means in this context. Depending on the requirement, it may refer to:
- The full SOAP envelope, including Header and Body
- Only the SOAP body payload
- The exact byte stream sent over HTTP
In most cases, retrieving the SOAP envelope as a string is sufficient for logging and debugging. However, if we require exact byte-level accuracy for compliance or forensic logging, we may need to intercept the transport layer instead of relying solely on framework-level APIs.
With that clarification in mind, let’s examine the most common implementation approaches.
3. Using SAAJ and SOAPMessage
If we’re working directly with SOAPMessage, extracting the raw XML is straightforward. The message can be written into an output stream and converted into a string.
Let’s consider the following example:
public static String soapMessageToString(SOAPMessage message) {
try {
if (message == null) {
throw new IllegalArgumentException("SOAPMessage cannot be null");
}
message.saveChanges();
ByteArrayOutputStream out = new ByteArrayOutputStream();
message.writeTo(out);
return out.toString(StandardCharsets.UTF_8.name());
} catch (Exception e) {
throw new RuntimeException("Failed to convert SOAPMessage to String", e);
}
}
In this example, we call saveChanges() to ensure that any modifications to the SOAP headers or body are applied before serialization. The writeTo(OutputStream) method writes the complete SOAP envelope, including header and body, into the ByteArrayOutputStream.
Finally, we convert the output stream into a UTF-8 string representation. This approach is simple and reliable for logging and debugging purposes.
4. Using JAX-WS with SOAPHandler
When we use JAX-WS, the cleanest way to capture raw SOAP XML is to plug into the message pipeline with a SOAPHandler. To keep the code generic and suitable for unit testing, we should not print directly. Instead, we can forward captured XML to a small interface that we can later implement using any logging framework, persistence layer, or test recorder.
Let’s consider the following example:
public class RawSoapCaptureHandler implements SOAPHandler<SOAPMessageContext> {
public interface SoapXmlSink {
void accept(Direction direction, String soapXml);
}
public enum Direction {
OUTBOUND,
INBOUND,
FAULT
}
private final SoapXmlSink sink;
public RawSoapCaptureHandler(SoapXmlSink sink) {
this.sink = sink;
}
@Override
public boolean handleMessage(SOAPMessageContext context) {
Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
Direction direction = Boolean.TRUE.equals(outbound) ? Direction.OUTBOUND : Direction.INBOUND;
String xml = toString(context.getMessage());
sink.accept(direction, xml);
return true;
}
@Override
public boolean handleFault(SOAPMessageContext context) {
String xml = toString(context.getMessage());
sink.accept(Direction.FAULT, xml);
return true;
}
@Override
public void close(MessageContext context) {
}
@Override
public Set<QName> getHeaders() {
return Collections.emptySet();
}
private String toString(SOAPMessage message) {
try {
message.saveChanges();
ByteArrayOutputStream out = new ByteArrayOutputStream();
message.writeTo(out);
return out.toString(StandardCharsets.UTF_8.name());
} catch (Exception e) {
throw new RuntimeException("Failed to serialize SOAP message", e);
}
}
}
In this implementation, we intercept both inbound and outbound SOAP messages using handleMessage(), and we intercept SOAP faults using handleFault(). We determine the message direction using MESSAGE_OUTBOUND_PROPERTY, then serialize the SOAP envelope with SOAPMessage.writeTo(OutputStream).
Instead of printing, we pass the raw XML to SoapXmlSink. This keeps the handler framework-neutral and easy to test. In unit tests, we can provide a sink that stores messages in memory. In production, we can provide a sink that forwards the XML to a logger, a database, or a monitoring system.
5. Using Apache CXF Interceptors
If our application uses Apache CXF, the framework provides built-in interceptors that simplify SOAP message logging.
Let’s consider the following example:
Client client = ClientProxy.getClient(port);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
In this case, we obtain the CXF Client from the generated service proxy. We then register LoggingInInterceptor and LoggingOutInterceptor.
These interceptors automatically log the full SOAP envelope for incoming and outgoing messages. CXF internally manages stream buffering to avoid the risk of accidentally consuming the message stream.
6. Using Spring Web Services
When we use Spring Web Services, we can capture SOAP XML using a ClientInterceptor. As with the JAX-WS handler, we should avoid printing and forward the raw XML to a generic sink so that we can plug in logging or tests later.
Let’s consider the following example:
public class SpringSoapCaptureInterceptor implements ClientInterceptor {
public interface SoapXmlSink {
void accept(Direction direction, String soapXml);
}
public enum Direction {
REQUEST,
RESPONSE,
FAULT
}
private final SoapXmlSink sink;
public SpringSoapCaptureInterceptor(SoapXmlSink sink) {
this.sink = sink;
}
@Override
public boolean handleRequest(MessageContext messageContext) {
String xml = toString(messageContext.getRequest());
sink.accept(Direction.REQUEST, xml);
return true;
}
@Override
public boolean handleResponse(MessageContext messageContext) {
String xml = toString(messageContext.getResponse());
sink.accept(Direction.RESPONSE, xml);
return true;
}
@Override
public boolean handleFault(MessageContext messageContext) {
String xml = toString(messageContext.getResponse());
sink.accept(Direction.FAULT, xml);
return true;
}
private String toString(WebServiceMessage message) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
message.writeTo(out);
return out.toString(StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("Failed to serialize Spring WS message", e);
}
}
}
In this example, we capture the raw SOAP XML for requests, responses, and faults. Spring WS provides the message as a WebServiceMessage, and the writeTo(OutputStream) method serializes the full SOAP envelope.
By forwarding the XML to SoapXmlSink, we keep the interceptor generic and reusable. We can later connect it to our preferred logging framework, or we can plug in a test sink that asserts the captured XML without relying on console output.
7. Important Considerations
When retrieving raw SOAP XML, several important factors must be considered.
First, encoding is typically UTF-8, but we should verify it if byte-level accuracy is required. Additionally, some frameworks rely on internal input streams. If we read from a stream without proper buffering, we may consume it and disrupt further processing.
Beyond technical handling, logging full SOAP messages in production environments may impact performance and increase memory usage. For this reason, it is best to enable detailed logging conditionally.
Finally, we must consider security. SOAP envelopes may contain sensitive information such as authentication tokens or personal data. Therefore, we must ensure proper log sanitization and compliance with security policies.
We should also be cautious when handling very large SOAP messages. Serializing large payloads into memory using ByteArrayOutputStream may increase memory consumption in high-throughput systems. In such cases, we should evaluate streaming or size-limited logging strategies.
8. Conclusion
Retrieving raw XML from a SOAP message in Java is a common requirement in enterprise systems. Whether we work directly with SOAPMessage, intercept messages using JAX-WS handlers, or rely on framework-specific solutions such as Apache CXF interceptors, the underlying principle remains the same. We serialize the SOAP envelope safely and convert it into a readable format.
By understanding these techniques, we gain deeper insight into SOAP communication and improve our ability to debug, monitor, and maintain service integrations effectively.
As always, the complete source code for the tutorial is available over on GitHub.
















