AX / D365FO – Create an xml file and download into the browser with File::SendFileToUser #d365fo #ax #msdyn365fo

To create an xml file you can use XmlNode class and if you want to save it into a folder you can use save method, but if you want to send to the user using the browser download functionality you have to use File::SendFileToUser method.

This method accepts only a MemoryStream so you must convert the xml to this data type before to use it.

This code shows how to do it

class XMLWriteEmplAddr
{
    public static void main(Args _args)
    {
        XMLDocument xmlDoc = XMLDocument::newBlank();
        XMLNode rootNode;
        XMLNode NodeEmpl, NodeName, NodeAddr;
        XMLElement xmlElement;
        XMLText xmlText;
        HCMWorker HCMWorker;

        xmlDoc = XMLDocument::newBlank();

        // Create first line containing version info
        rootNode = xmlDoc.documentElement();
        xmlElement = xmlDoc.createElement('EmployeeList');
        rootNode = xmlDoc.appendChild(xmlElement);

        while select HCMWorker
        {
            // Create a node for the Employee record
            xmlElement = xmlDoc.createElement('Employee');
            NodeEmpl = rootNode.appendChild(xmlElement);
 
            // Create a node for the name
            xmlElement = xmlDoc.createElement('EmplName');
            NodeName = NodeEmpl.appendChild(xmlElement);
            xmlText =xmlDoc.createTextNode(HCMWorker.Name());
            NodeName.appendChild(xmlText);
 
            // Create a node for the address
            xmlElement = xmlDoc.createElement('EmplEmail');
            NodeAddr = NodeEmpl.appendChild(xmlElement);
            xmlText = xmlDoc.createTextNode(HCMWorker.email());
            NodeAddr.appendChild(xmlText);
        }

        // Save the file
        XMLWriteEmplAddr::writeXmlFile(xmlDoc);

    }


    public static void writeXmlFile(XmlDocument _xmlDoc)
    {
        using (var stream = new System.IO.MemoryStream())
        {
            XMLWriter writer = XMLWriter::newStream(stream); //Convert the Xml to a memory stream and pass it to use File::SendFileToUser method
            _xmlDoc.writeTo(writer);
            writer.flush();

            File::SendFileToUser(stream, 'XmlFile.xml');
        }
    }

}

Xml file will be dowloaded into the browser

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s