How do Apex developers parse complex XML responses received from legacy SOAP or REST web services?
Answer
Basics: Many legacy systems answer in XML (SOAP envelopes, REST with application/xml). Apex has no one-line XML-to-object converter like JSON.deserialize, so you parse manually. Dom.Document.load(String) builds the whole tree in memory; getRootElement() returns the root Dom.XmlNode.
How it works:
- Receive
HttpResponse res, thenDom.Document doc = new Dom.Document(); doc.load(res.getBody()); Dom.XmlNode root = doc.getRootElement();- Navigate with
getChildElement(name, namespaceUri),getChildElements(),getName(),getText(),getAttributeValue(name, namespaceUri). - For SOAP, drill through
EnvelopethenBodythen the response element, each in its own namespace. - Map values into your own wrapper or sObject lists, then do DML once.
Advanced / deep dive: Dom.Document loads the full tree, so heap (6 MB sync, 12 MB async) is the constraint on big payloads. XmlStreamReader is a forward-only pull parser (hasNext(), next(), getEventType(), getLocalName(), getText()) that uses far less heap and suits large lists, but is more verbose. For a SOAP service with a WSDL, generate Apex stubs (Setup, Apex Classes, Generate from WSDL), which handle serialization and namespaces and are mockable via WebServiceMock. For plain REST, always prefer JSON if the provider offers it. XML you generate can be built with too (, ) or .