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

Apex class object to XML

Is there a way in salesforce or any API that can convert a apex class object to an xml dynamically.

Ex: If I have a class like this

public class Sample{

       String firstName;

       String lastName;

       String phone;



Can I get an xml out that class like







I know we can do it by using Document and XMLNode classes, but we have to add the child elements hardcoded.

Is there any way to build xml dynamically.






AFAIK, there's no "toXML" functionality for an SObject in Apex, but the SOAP and REST API can both return results in XML.  What's the use case?


I have to construct the soap body and request to pass it in http.send() to call web service on our internal systems and for that the xml has be dynamic.


Have you looked into outbound messaging?


we want to make a synchronous call to the web service. I doubt if we can do that with OM


You're right. Outbound Messaging is definitely asynchronous. You'll have to roll your own toXML using the XML classes provided by Apex.