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
ismyhcismyhc 

How to get text of multiple xml elements with the same name using Xmlnode

Im trying to return the text of multiple xml elements with the same name. Im using Xmlnode.

 

Heres part of the code that handles the response:

 

// Get xml body from response
dom.Document docx = res.getBodyDocument();
dom.Xmlnode xroot = docx.getRootElement();
dom.Xmlnode xrec = xroot.getChildElement('error', null);

// Setup email for exception
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();            
String[] toAddress = new String[] {ownerEmail};
mail.setToAddresses(toAddress);
mail.setSenderDisplayName('Salesforce');
mail.setSubject('A problem has occured with creating the Proposal');
mail.setPlainTextBody('The following error occured when trying to create the Proposal: \n\n"Proposal ' + newError + '"\n\nPlease correct the errors above and try again.');    
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

 

The reponse would look something like:

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<errors>
    <error>advertiser can't be blank</error>
    <error>name can't be blank</error>
    <error>campaign_type can't be blank</error>
    <error>start_date can't be blank</error>
</errors>

 

Right now it only returns the text from the first "error" element.

 

Ive looked at the xmlnode docs, but Im having a hard time understanding how to get the text from all of the nodes.

 

Any help would be much appreciated!!


Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
Sam961Sam961

hiii 

 

u can use xroot.getchildren method so that u can retrive all the 4 chailds and ten use a loop to get all the four strings ..

 

All Answers

Sam961Sam961

hiii 

 

u can use xroot.getchildren method so that u can retrive all the 4 chailds and ten use a loop to get all the four strings ..

 

This was selected as the best answer
ismyhcismyhc

Ah.. Yes this worked out. Below is what I ended up doing incase someone else may want to know.

 

dom.Document docx = res.getBodyDocument();
dom.Xmlnode xroot = docx.getRootElement();
List<dom.Xmlnode> xerrors = new List<dom.Xmlnode>();
xerrors = xroot.getChildren();

String errorMessages = '';
for (dom.Xmlnode i : xerrors)
{
    errorMessages += '- ' + string.valueOf(i.getText()).trim() + '\n';
}

 Thanks!
Jacob