SOAP Envelope XML to JSON Conversion
Convert SOAP XML messages to JSON for modern API integration. Covers envelope structure, headers, body extraction, fault handling, and namespace stripping strategies.
Detailed Explanation
SOAP (Simple Object Access Protocol) uses XML as its message format. Converting SOAP envelopes to JSON is one of the most common real-world XML-to-JSON tasks, especially when building API gateways or middleware.
A typical SOAP response:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns="http://example.com/api">
<soap:Header>
<ns:RequestId>REQ-12345</ns:RequestId>
</soap:Header>
<soap:Body>
<ns:GetUserResponse>
<ns:User>
<ns:Id>42</ns:Id>
<ns:Name>Alice Johnson</ns:Name>
<ns:Email>alice@example.com</ns:Email>
<ns:Role>admin</ns:Role>
</ns:User>
</ns:GetUserResponse>
</soap:Body>
</soap:Envelope>
Extracted JSON (namespace-stripped, body only):
{
"GetUserResponse": {
"User": {
"Id": "42",
"Name": "Alice Johnson",
"Email": "alice@example.com",
"Role": "admin"
}
}
}
SOAP-to-JSON conversion strategies:
- Full conversion -- convert the entire envelope including headers. Useful for logging and debugging.
- Body extraction -- skip the envelope and headers, convert only the
<Body>content. Most common for API integration. - Unwrapped response -- extract just the response object inside the body, stripping both the envelope and the operation wrapper. Produces the cleanest JSON.
Handling SOAP faults:
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Internal server error</faultstring>
<detail>
<errorCode>DB_TIMEOUT</errorCode>
</detail>
</soap:Fault>
</soap:Body>
Converts to:
{
"Fault": {
"faultcode": "soap:Server",
"faultstring": "Internal server error",
"detail": {
"errorCode": "DB_TIMEOUT"
}
}
}
Namespace handling in SOAP:
SOAP responses are heavily namespaced. For JSON output, you typically:
- Strip all namespace prefixes (
ns:NamebecomesName) - Remove
xmlnsdeclarations - Preserve only the element local names
This produces clean, readable JSON at the cost of losing namespace information. If multiple namespaces define elements with the same local name, you may need to preserve prefixes or use a different strategy.
Use Case
Building an API gateway that translates SOAP responses from legacy banking services into clean JSON for consumption by a modern mobile banking application.