[SalesForce] how to parse XML file having nested tags using XmlStreamReader

my xml string is below –

<articles>
<article>
    <source>EN-US</source>
    <target>SL</target>
    <id>ka1800000000eCYAAY</id>
    <publishstatus>Draft</publishstatus>
    <fields>
        <field name="BU_Type_SMB__c" translate="false">false</field>
        <field name="BU_Type__c" translate="false">RBU</field>
        <field name="BU_Type_text__c" translate="false">HCP</field>
        <field name="Auto_Assignment_Rule_Enabled__c" translate="false">false</field>
    </fields>
</article>

I have tried like this –

public void XMLParsingUsingStreamreader(){


    string xml = '<articles><article><source>EN-US</source><target>SL</target><id>ka1800000000eCYAAY</id><publishstatus>Draft</publishstatus><fields><field name="BU_Type_SMB__c" translate="false">false</field><field name="BU_Type__c" translate="false">RBU</field><field name="BU_Type_text__c" translate="false">HCP</field><field name="Auto_Assignment_Rule_Enabled__c" translate="false">false</field></fields></article></articles>';
    XmlStreamReader xsr = new XmlStreamReader(xml);
    //system.debug('-------getLocalname------'+xsr.getLocalName());


        while(xsr.hasNext()){

            system.debug('---------Event_type-------'+xsr.getEventType());
            if(xsr.getEventType() == XmlTag.START_ELEMENT){
                system.debug('-------getLocalname------'+xsr.getLocalName());
                if('article' == xsr.getLocalName()){
                    if('source' == xsr.getLocalName()){
                        if(xsr.getEventType() == XmlTag.END_ELEMENT){
                            break;
                        }else if(xsr.getEventType() == XmlTag.CHARACTERS){
                            //String source = xsr.getText();
                            system.debug('------source--------'+xsr.getText());
                            break;
                        }
                    }
               } 
            }
            xsr.next();
        }

    }

but I'm not able to get the text inside the tags. Plz help me with that.

Best Answer

It looks like you need to loop through the inner elements of your XML. You are accessing the 'article' localname but then you are not looping through the elements within 'article'. There are a variety of ways to do this but essentially you must move the pointer over the inner elements to fetch the desired text. SFDC dev docs has an example you can rewire to meet your needs... notice the method called to parse the book tag and fetch the inner elements. That is where you are getting stuck. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_xml_streaming_reading.htm

Parsing XML is time consuming and nuanced but can lead to much more concise code than what WSDL to Apex offers using the object method depending on your WSDL.

Related Topic