'How to parse XML string in Salesforce using Apex?

<Layout xmlns="http://soap.sforce.com/2006/04/metadata">
    <excludeButtons>Submit</excludeButtons>
    <layoutSections>
        <customLabel>false</customLabel>
        <detailHeading>false</detailHeading>
        <editHeading>true</editHeading>
        <label>Information</label>
        <layoutColumns>
            <layoutItems>
                <behavior>Readonly</behavior>
                <field>Hyperlink__c</field>
            </layoutItems>
        </layoutColumns>
        <layoutColumns/>
        <style>TwoColumnsTopToBottom</style>
    </layoutSections>
    <layoutSections>
        <customLabel>false</customLabel>
        <detailHeading>false</detailHeading>
        <editHeading>true</editHeading>
        <label>ABC</label>
        <layoutColumns>
            <layoutItems>
                <behavior>Readonly</behavior>
                <field>TOTAL__c</field>
            </layoutItems>
            <layoutItems>
                <behavior>Readonly</behavior>
                <field>SUBTOTAL__c</field>
            </layoutItems>
        </layoutColumns>
        <layoutColumns/>
        <style>TwoColumnsTopToBottom</style>
    </layoutSections>
</Layout>                                                                                              
                                                                                                  

Above code is input as a xml file now I want to convert this code in to given below output. output:Information - Hyperlink__c ABC - TOTAL__c, SUBTOTAL__c

please any one help me, its important to me. Thanks. 


Solution 1:[1]

I would start by assigning the input xml to an XML Dom Document, for example:

Dom.Document doc = new Dom.Document();
doc.load(xml);

Then, you can access its attributes like this:

Dom.XMLNode layout = doc.getRootElement();
Dom.XmlNode[] layoutSections = layout.getChildElements();

Once you have access to the layout sections, you can loop through them and access specific child elements with:

String label = layoutSection.getChildElement('label', null).getText();

Note that a layoutSection is of type XmlNode which means you can keep going through its child elements and access its values.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1