Generate XML data in Apex

by Rijwan Mohmmed
how-to-generate-xml-data-in-apex-techdicer

Hello friends, today we are going to discuss How to Generate XML data in Apex Salesforce.

XML is one of the most effective means of sending and receiving files over the internet. Additionally, you should be able to parse and create XML files for us. My previous blog showed you how to parse XML files in Apex. However, I will show you how to generate an XML file in Apex using the following example.

Also check this: How to Parse XML data in Apex

Key Highlights :

  1. Use a class DOM.Document which is used to create XML files.
  2. Use createRootElement for add root elements
  3. Use addChildElement for add child elements.

Code :

TechdicerXMLGenerator.cls : Generate XML data in Apex Salesforce

public class TechdicerXMLGenerator {
	
    public static void xmlGenerator(){
        String xmlstring = '';
        
        DOM.Document doc = new DOM.Document();
        
        dom.XmlNode results = doc.createRootElement('Results', null, null);
        dom.XmlNode body1 = results.addChildElement('Account', null, null);

        body1.addChildElement('UserId', null, null).addTextNode('userId');
        body1.addChildElement('Active', null, null).addTextNode('true');

        dom.XmlNode body2 = results.addChildElement('Quotes', null, null);
        
		dom.XmlNode body2Child = body2.addChildElement('Company', null, null);
        body2Child.addChildElement('Name', null, null).addTextNode('Test1');
        body2Child.addChildElement('Type', null, null).addTextNode('IT');
        
        dom.XmlNode body3Child = body2.addChildElement('Company', null, null);
        body3Child.addChildElement('Name', null, null).addTextNode('Test1');
        body3Child.addChildElement('Type', null, null).addTextNode('IT');

        xmlstring = doc.toXmlString();
        System.debug('xmlstring==> ' + xmlstring);
    }
}

Output :

<?xml version="1.0" encoding="UTF-8"?>
<Results>
	<Account>
		<UserId>userId</UserId>
		<Active>true</Active>
	</Account>
	<Quotes>
		<Company>
			<Name>Test1</Name>
			<Type>IT</Type>
		</Company>
		<Company>
			<Name>Test1</Name>
			<Type>IT</Type>
		</Company>
	</Quotes>
</Results>

Reference :

  1. XML in Salesforce

What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
3
+1
0

You may also like

Leave a Comment