# How do Apex developers parse complex XML responses received from legacy SOAP or REST web services?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, XML Parsing, DOM Document

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. Receive `HttpResponse res`, then `Dom.Document doc = new Dom.Document(); doc.load(res.getBody());`
2. `Dom.XmlNode root = doc.getRootElement();`
3. Navigate with `getChildElement(name, namespaceUri)`, `getChildElements()`, `getName()`, `getText()`, `getAttributeValue(name, namespaceUri)`.
4. For SOAP, drill through `Envelope` then `Body` then the response element, each in its own namespace.
5. 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 `Dom.Document` too (`createRootElement`, `addChildElement`) or `XmlStreamWriter`.

**Code / config example:**
```apex
public static List<String> parseOrderIds(String xml) {
    List<String> ids = new List<String>();
    Dom.Document doc = new Dom.Document();
    doc.load(xml);
    Dom.XmlNode root = doc.getRootElement();            // <Orders xmlns="urn:erp">
    String ns = root.getNamespace();
    for (Dom.XmlNode order : root.getChildElements()) {
        if (order.getName() == 'Order') {
            Dom.XmlNode idNode = order.getChildElement('Id', ns);
            if (idNode != null) ids.add(idNode.getText());
        }
    }
    return ids;
}
```

**Hidden gotchas & must-remember points:**
- Forgetting the namespace is the number one bug: `getChildElement('Id', null)` returns null when the element has a default namespace.
- `getText()` returns only that node's own text, not descendants.
- Whitespace/text nodes are not returned by `getChildElements()`, which returns elements only.
- Malformed XML throws `XmlException`; wrap `load` in try/catch.
- Parse results are not typed: convert dates and numbers yourself and null-check every node.

**Best practice:** Isolate parsing in one tested class, use WSDL2Apex for real SOAP services, and switch to `XmlStreamReader` when payloads approach a meaningful share of the heap limit.

---
Source: ForceChallenges · last updated 2026-11-02
