Site icon WedgeCommerce

How to generate XML in APEX

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.

OUTPUT

The output of the XML page will be like:

 

Support

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

https://wedgecommerce.com/contact-us/

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

Exit mobile version