function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
John IssaJohn Issa 

How to capture specific value in XML using DOM

Hello,

I'm currently trying to parse an xml file that I retreive via an API call.  My dataset is relatively close to what is given in this example: 

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_xml_dom.htm

When I go through my example, I can only return the values found in the first node.

If I have an xml file that has multiple nodes of the same value (i.e address and name), how would I parse the value to retreive a specific value?

For example:  If I wanted to return the city in which the addres of 555 2nd Street is found, how would I go about doing that?
 
<info>
<address>
    <name>Kirk Stevens</name>
    <street1>808 State St</street1>
    <street2>Apt. 2</street2>
    <city>Palookaville</city>
    <state>PA</state>
    <country>USA</country>
</address>
<address>
    <name>John Smith</name>
    <street1>8078 1st St</street1>
    <street2>Apt. 15</street2>
    <city>Gainsville</city>
    <state>GA</state>
    <country>USA</country>
</address>
<address>
    <name>Jim Brown</name>
    <street1>555 2nd St</street1>
    <street2></street2>
    <city>Orlando</city>
    <state>FL</state>
    <country>USA</country>
</address>
</info>
 
public class DomDocument {
 
    // Pass in the URL for the request
    // For the purposes of this sample,assume that the URL
    // returns the XML shown above in the response body
    public void parseResponseDom(String url){
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        // url that returns the XML in the response body
        req.setEndpoint(url);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        Dom.Document doc = res.getBodyDocument();
        
        //Retrieve the root element for this document.
        Dom.XMLNode address = doc.getRootElement();
        
        String name = address.getChildElement('name', null).getText();
        String state = address.getChildElement('state', null).getText();
        // print out specific elements
        System.debug('Name: ' + name);
        System.debug('State: ' + state);
        
        // Alternatively, loop through the child elements.
        // This prints out all the elements of the address
        for(Dom.XMLNode child : address.getChildElements()) {
           System.debug(child.getText());
        }
    }
}