2

(i) Is it possible to directly serialize/deserialize sObject record to xml in apex code?

(ii) Is it possible to serialize/deserialize apex object to/from xml?

  • 1
    Note that serialization to JSON is available through JSON.serialize so if the serialization format is under your control I suggest your promote JSON as the solution. – Keith C Aug 20 '15 at 7:44
4

Answer for both questions is NO. At least directly.

Salesforce currently doesn't support direct serialisation of objects into XML format. You can only parse or create XML using XMLDom and XMLStreamWriter. So, as a work around you need to create xml nodes by writing xml using XMLStreamWriter.

Another workaround: I have this solution for a long time which serialise Sobjects. It requires call out. Not sure it still works but you can try it.

//Rest Service in Salesforce
@restresource(/urlmapping='/xmlSerializationSerivice/*') 
global class  XmlListExposer 
{

  @httpPost
  global static List<Account> getAccounts()
  {
     return [SELECT Id, Name FROM Account limit 200];
  } 
}


// Webservice in Salesforce
global class XMLSerializationUtility
{

    webservice static staing getAccountsInXML()
    {

      Httprequest req=new Httpreques();
      req.setendpoint(URL.getCurrentRequestUrl().toExternalForm()+'/services/apexrest/xmlSerializationSerivice.xml');
      req.setmethod('POST');
      req.setheader('Authorization'.'OAuth '+userinfo.getsessionid());

      try
      {
        Http h=new Http();
        httpresponse r= h.send(req); 
        System.debug(''+r.getbody());
      }
      catch(Exception ex)
      {
        System.debug(''+rex.getMessage());
      }
    } 
}
| improve this answer | |
0

Just so that someone may benefit from it, I wrote XML serializer which can serialize/deserialize apex objects to and from XML. Check it out here: https://github.com/skolakan/Apex-XML-Serializer

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.