XML Basics in Apex
By the end of this lesson, you'll be able to:
- Parse an XML response using the DOM.Document class
- Navigate an XML structure to extract specific values
- Recognize when an integration might use XML instead of JSON
Prerequisites: "JSON Serialization and Deserialization"
When XML still shows up
Most modern APIs use JSON, but XML remains common in specific contexts: SOAP web services (next lesson), older enterprise systems, and some legacy government or financial integrations. Recognizing XML and knowing how to parse it is still a genuinely useful skill, even though JSON dominates newer integrations.
Parsing XML with DOM.Document
String xmlBody = '<response><status>success</status><rate>45.50</rate></response>';
DOM.Document doc = new DOM.Document();
doc.load(xmlBody);
DOM.XMLNode root = doc.getRootElement();
String status = root.getChildElement('status', null).getText();
Decimal rate = Decimal.valueOf(root.getChildElement('rate', null).getText());
doc.load(xmlBody) parses the raw XML text; getRootElement() gives access to the top-level <response> node, and getChildElement(name, namespace) navigates down to a specific child — here, null for the namespace since this XML doesn't use one.
Navigating a more nested structure
String xmlBody = '<order><items><item><name>Widget</name><qty>3</qty></item></items></order>';
DOM.Document doc = new DOM.Document();
doc.load(xmlBody);
DOM.XMLNode itemNode = doc.getRootElement().getChildElement('items', null).getChildElement('item', null);
String itemName = itemNode.getChildElement('name', null).getText();
Integer qty = Integer.valueOf(itemNode.getChildElement('qty', null).getText());
Each getChildElement call navigates one level deeper — reading nested XML is a matter of chaining these calls to walk down the structure exactly the way the XML itself is nested.
Exercise
Given XML '<product><name>Widget</name><price>49.99</price></product>', parse it and extract both the name and price.
Show hint
getChildElement('name', null).getText() and similarly for price.
XML Basics in Apex Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Some external systems — especially older or enterprise ones — still exchange data as XML rather than JSON; Apex's DOM classes parse and navigate it directly.