+ Start a Discussion
Sunny_SlpSunny_Slp 

XML version of record

I'm trying to create an XML document from a select set of fields of an object. I decided to use XmlStreamWriter class.

 

To write <fieldlabel1>fieldlabel1_value</fieldlabel1>

              <fieldlabel2>fieldlabel2_value</fieldlabel2> and so on

 

I made a List<string> fieldstoInclude that has all the fields to include in XML

 

              for(String s : fieldstoInclude){
                 w.writeStartElement(null,s,null);
                 //how to write value?
                 w.writeEndElement();
                }

My question here is, since WriteCharacter only takes Text and fields of an object can be of varying types, what is the best way to go ahead and do this?

 

I was thinking of making a map<string,string> with field labels as Map's keys and field values converted into strings as Map's value. There are hundereds of fields and I don't want to write code to convert each field manually. Is there a way to do this?

 

Any help will be greatly appreaciated.

 

Thank you,

Sunny_Slp

Best Answer chosen by Admin (Salesforce Developers) 
spraetzspraetz

I assume you have some custom or standard object with fields on it.  We'll call it sObject__c for now.

 

//Retrieve the object

sObject__c so = [SELECT blah blah from sObject__c WHERE blah blah=];

 

for(String s : fieldsToInclude){

w.writeStartElement, null, s, null)

w.writeCharacters(String.valueOf(so.get(s)));

w.writeEndElement()

}

 

I think that should work.  Every field type has string representation that can be accessed via String.valueOf().  Combine that with the .get(String fieldName) that is inherrent to all sObjects and you should be good to go.

All Answers

spraetzspraetz

I assume you have some custom or standard object with fields on it.  We'll call it sObject__c for now.

 

//Retrieve the object

sObject__c so = [SELECT blah blah from sObject__c WHERE blah blah=];

 

for(String s : fieldsToInclude){

w.writeStartElement, null, s, null)

w.writeCharacters(String.valueOf(so.get(s)));

w.writeEndElement()

}

 

I think that should work.  Every field type has string representation that can be accessed via String.valueOf().  Combine that with the .get(String fieldName) that is inherrent to all sObjects and you should be good to go.

This was selected as the best answer
Sunny_SlpSunny_Slp

Thank you Ryan.