Custom XML Object in Salesforce

Create a Custom XML in apex code

Apex is the coding language for Salesforce cloud computing.

Salesforce provides a Class ‘XmlStreamWriter’ using which one can write a Custom XML object and convert it to String type.

Below is the code snippet for the same:

XmlStreamWriter xmlWriterObj = new XmlStreamWriter();
        
xmlWriterObj.writeStartElement(null, 'Wrapper', null);
xmlWriterObj.writeAttribute(null, null, 'ContainerCount', '2');

xmlWriterObj.writeStartElement(null, 'ContainerOne', null);
	xmlWriterObj.writeAttribute(null, null, 'InnerElementCount', '1');				
	xmlWriterObj.writeStartElement(null, 'InnerContainerOne', null);
	xmlWriterObj.writeCharacters('This is the 1st Inner Child of Container');
	xmlWriterObj.writeEndElement();
xmlWriterObj.writeEndElement();

xmlWriterObj.writeStartElement(null, 'ContainerTwo', null);
xmlWriterObj.writeCharacters('This is the 2nd Child of wrapper');
xmlWriterObj.writeEndElement();

xmlWriterObj.writeEndElement();        
String xmlAsString = xmlWriterObj.getXmlString();

xmlWriterObj.close();

The output of the above snippet when debugged will give:

customxmlcapture

Decoding each method of the XmlStreamWriter class:

  1. writeStartElement : This creates the Start of the XML tag
  2. writeAttribute : This adds an attribute with key-value to the parent tag
  3. writeCharacters : This writes text/value for a tag
  4. writeEndElement : This creates the End of the XML tag

Happy Coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s