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
Bryan TelfordBryan Telford 

Parsing repeating xml nodes

Does anyone know how to use the XML DOM to parse repeating nodes of XML? For example, let's say I have the following section.
        <_CREDIT_SCORE>
                <_CREDIT_SCORE _CreditScore="668" _ReportingAgency="Experian"/>
                <_CREDIT_SCORE _CreditScore="658" _ReportingAgency="TransUnion"/>
                <_CREDIT_SCORE _CreditScore="660" _ReportingAgency="Equifax"/>
            </_CREDIT_SCORE>
I need to use the DOM to parse the first _CREDIT_SCORE element, then the second, and third. Ultimately, I need the get the values of the attributes inside each _CREDIT_SCORE node.

The Salesforce documentation provided doesn't seem to have a way to do this. For example, using getChildElement will always return the first element. I need to be able to read each _CREDIT_SCORE.  

I've been struggling with this for weeks. It seems like it should be a fairly easy task, but using the DOM provided by Salesforce, there doesn't seem to be a way to get to the subsequent nodes after the first. Perhaps I've missed something in my reading of the documentation, or perhaps there is another way altogether. 

Thanks for any help!
 
Best Answer chosen by Bryan Telford
pconpcon
You can do this by iterating the XMLNodes using getChildElements
 
String xmlData = '<?xml version="1.0"?>' +
    '<_CREDIT_SCORE>' +
    '  <_CREDIT_SCORE _CreditScore="668" _ReportingAgency="Experian"/>' +
    '  <_CREDIT_SCORE _CreditScore="658" _ReportingAgency="TransUnion"/>' +
    '  <_CREDIT_SCORE _CreditScore="660" _ReportingAgency="Equifax"/>' +
    '</_CREDIT_SCORE>';

Dom.Document doc = new Dom.Document();
doc.load(xmlData);
for (Dom.XmlNode node : doc.getRootElement().getChildElements()) {
    System.debug(node.getAttributeValue('_ReportingAgency', ''));
}

You can use the .getName() on the node to verify that you are in _CREDIT_SCORE

All Answers

pconpcon
You can do this by iterating the XMLNodes using getChildElements
 
String xmlData = '<?xml version="1.0"?>' +
    '<_CREDIT_SCORE>' +
    '  <_CREDIT_SCORE _CreditScore="668" _ReportingAgency="Experian"/>' +
    '  <_CREDIT_SCORE _CreditScore="658" _ReportingAgency="TransUnion"/>' +
    '  <_CREDIT_SCORE _CreditScore="660" _ReportingAgency="Equifax"/>' +
    '</_CREDIT_SCORE>';

Dom.Document doc = new Dom.Document();
doc.load(xmlData);
for (Dom.XmlNode node : doc.getRootElement().getChildElements()) {
    System.debug(node.getAttributeValue('_ReportingAgency', ''));
}

You can use the .getName() on the node to verify that you are in _CREDIT_SCORE
This was selected as the best answer
Bryan TelfordBryan Telford
Thank you, pcon! That was exactly what I needed and it worked beautifully.