Reading list Switch to dark mode

    How to generate XML in APEX

    Updated 16 July 2021

    As we all know that XML is one of the best methods to send or receive files over the internet. And to provide us support for parsing and creating XML files. In one of my previous blogs I have taught you how to parse XML files in apex. However in this example I’ll show you how we can generate XML file in apex.

    APEX Code

    The Apex code to create an XML file is as follows:

    public class XMLgen {
        public string xmlstring { get; set;}
        public XMLgen(){
            DOM.Document doc = new DOM.Document();
            dom.XmlNode products = doc.createRootElement('products', null, null);
            dom.XmlNode body1= products.addChildElement('product', null, null);
            body1.addChildElement('Name', null, null).addTextNode('Xbox One');
            body1.addChildElement('Code', null, null).addTextNode('XBO');
            dom.XmlNode body2= products.addChildElement('product', null, null);
            body2.addChildElement('Name', null, null).addTextNode('PlayStation 4');
            body2.addChildElement('Code', null, null).addTextNode('PS4');
            dom.XmlNode body3= products.addChildElement('product', null, null);
            body3.addChildElement('Name', null, null).addTextNode('WII');
            body3.addChildElement('Code', null, null).addTextNode('Wii');
            xmlstring = doc.toXmlString();

    We have used a class DOM.Document which is used to create XML files. Next we create a new root node which will be held by a variable called ‘products’. This will be used to create child nodes and attributes of the root node.
    Next we will create child nodes, the value returned for these nodes could be held by the individual nodes if we want to create more sub nodes, like I have kept the value saved, so that text nodes could be added to these nodes.
    For every addChildElement() function there are three values, the name of the node, the namespace add the prefix for the node. I have kept the last two values as null, you can add it according to your need.
    Once it is done, the toXMLString() function returns the corresponding string of the XML file. Save it, and show it in a VF page, like I have done.


    The output of the XML page will be like:


    That’s all for how to use custom settings in salesforce, for any further queries feel free to add a ticket at:

    Searching for an experienced
    Salesforce Company ?
    Find out More

    Or let us know your views on how to make this code better, in comments section below.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*

    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home

    Table of Content