+ Start a Discussion

Generate XML dynamically


 I have to generate an XML to send as Request, from a list returned by a dynamic soql query.The fields to be queried from the object in the soql will be in my custom settings like name-Account,and fields to be queried in the record of account.

How do I generate XML, for dynamic object selected and its fields,suppose if I select object 'B', in my page,i should generate XML for the object B with the fields in the custom setting mapped to B or if its object A the fields for object A from the custom settings...

Thanks in Advance..
Can you put a sample of the XML request that you are looking for ?
 //getting the fields to be queried from custom setting
Template_Custom_Setting__c myCS1 = Template_Custom_Setting__c.getValues(oAccount.XML_Response__c);
//Question:how do i get the fields i.e values in each field of the above custom setting?? for now im splitting by comma,and then by = and based on the index positions in the array i am getting the fields into a string...called finalFields.
now from the query returned i have to generate XML with field label and its value dynamically 

xmlResponse  = 'Select Id'+finalFields+' from Account Where Id ='+' \''+CurrentPageId+'\'';
        Account Acc = Database.query(xmlResponse);

 XmlStreamWriter w = new XmlStreamWriter();
        w.writeStartDocument(null, '1.0'); 
        w.writeStartElement(null, 'accounts', null); 
        w.writeStartElement(null, 'account', null);
        w.writeStartElement(null, 'accountid', null); 
     w.writeStartElement(null, 'AccountName', null); 

something like this I will not always get AccountID,Account NAme ... the fields may differ based on the custom setting i select 
Below is a pseudo code : 

List<String> fieldNames = new List<String>();
for(Template_Custom_Setting__c thisCs : Template_Custom_Setting__c.getValues(objectName)){
    // Keep your splitting logic for getting the fields name as is.  
for(String thisField : fieldNames){
    finalFields =+ thisField;

String queryString = 'Select Id'+finalFields+' from Account Where Id ='+' \''+CurrentPageId+'\'';
List<sObject> sobjList = Database.query(queryString);
// Iterate over the list of field names. 
for(sObject thisRecord : sobjList){
    for(String thisField : fieldNames){
        system.debug('#### Field Name = '+thisField);
        system.debug('#### Field Value = '+thisRecord.get(thisField));
        // you can create your XML structure, with the above values.

If my suggestion(s) worked, do let me know by marking the answer as "Best Answer" right under the comment.
This will help the rest of the community should they have a similar issue in the future. 

Thank you..