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
leoSFDC 13leoSFDC 13 

how to export data in xml format in salesforce

v varaprasadv varaprasad
hi Leo,

Please check once below sample code : 
 
@Restresource(urlmapping = '/accounts/*')
Global class GenerateaccountXML {
   
    webservice static string generatexml(){
        xmlstreamwriter x = new xmlstreamwriter();
        list<account> acc = [SELECT AccountNumber,AccountSource,BillingCity,BillingCountry,DOB__c,Email__c,Name,
            (select name from contacts) FROM Account];
        string xmlstr = '';
        x.writeStartElement(null, 'Accounts', null);
        for(account a : acc){
            if(a.contacts.size()>0){
        x.writeStartElement(null, 'Account', null);
        x.writeCharacters(a.name);
        x.writeEndElement();
        x.writeStartElement(null, 'Accountbillingcity', null);
            if(a.BillingCity == null){
        x.writeCharacters('hyderabad');
            }else{
        x.writecharacters(a.BillingCity);
            }
        x.writeEndElement();
            x.writeStartElement(null, 'contacts', null);
            for(contact c : a.contacts){
                 x.writeStartElement(null, 'contactname', null);
                                     x.writeCharacters(c.name);
                                     x.writeEndElement();            
               
            }
            x.writeEndElement();
            }
        }
        x.writeEndElement();
        xmlstr = x.getXmlString();
        return xmlstr;       
    }
}


Execute following code in console :

string s = GenerateaccountXML.generatexml();
system.debug('account xml file is : ' +s);
More info : 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_xml_XmlStream_writer.htm

Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For Salesforce Project Support: varaprasad4sfdc@gmail.com

Salesforce latest interview questions  :
https://www.youtube.com/channel/UCOcam_Hb4KjeBdYJlJWV_ZA?sub_confirmation=1
Raj VakatiRaj Vakati
You dnt need to create a webservice for export the data into xml file .. 

What is your requirement .. can you explan ??