Monday, 30 March 2015

XML Parsing in Salesforce using DOM

Hi,

Below is a sample XML String and code to parse the same.

Sample XML: 

1. Just create a new text file and paste the below xml string in that.
2. Upload the file to document object with name "xml".



<Company>
<Department>
<Employee>
<Name>Venkat V</Name>
<City>London - XYZ</City>
<Country>UK</Country>
</Employee>
<Employee>
<Name>Kalyan</Name>
<City>Hyderabad</City>
<Country>IND</Country>
</Employee>
<Employee>
<Name>Teja</Name>
<City>Chennai</City>
<Country>India</Country>
</Employee>
</Department>
</Company>


Apex Code:


public with sharing class xmlParserClassNew {
    public String resp{get;set;}
    public PageReference doParse() {
        Document objD = [select id,name,body from Document where name ='xml'];
        blob response = objD.body;
        String strResponse = response.toString();
        System.debug('---strResponse--->'+strResponse);
        DOM.Document objDoc = new DOM.Document();
        objDOC.load(strResponse);
     
        List<Employee__c> empData = new List<Employee__c>();
     
        for(DOM.XMLNode dept : objDOC.getRootElement().getChildElements()){
            for(DOM.XMLNode emps : dept.getChildElements()){
                Employee__c objE = new Employee__c();
                for(DOM.XMLNode child : emps.getChildElements()){
                 
                    if(child.getName() == 'Name'){
                        objE.Name = child.getText();
                    }
                    if(child.getName() == 'City'){
                        objE.city__c = child.getText();
                    }
                    if(child.getName() == 'Country'){
                        objE.Country__c = child.getText();
                    }
                }
                empData.add(objE);

            }
        }
if(empData.size()>0)
Insert empData;
     
        return null;
    }
    public xmlParserClassNew(){
    }
}



No comments:

Post a Comment