AX / D365FO – Remove all child nodes of a Parent node in XML #d365fo #ax #msdyn365fo

Imagine that your requirement is to write an XML file with some nodes inside, but in a specific case you must remove all the child nodes of a Parent node you have already written.

Something like that:

If you want to remove all child nodes of a parent node in an XML file you can use RemoveAll() method :

class temp
{
    /// <summary>
    /// Runs the class with the specified arguments.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
        FileIoPermission permission;
        XMLDocument xmlDoc = XMLDocument::newBlank();
        XMLNode rootNode;
        XMLNode Node1, Node2;
        XMLElement xmlElement;
        str ns = 'http://www.w3.org/2001/XMLSchema-instance';

        permission= new FileIoPermission('C:\\Altitudo\\Test.xml','w');
        permission.assert();
        xmlDoc = XMLDocument::newBlank();

        //Parent node
        rootNode = xmlDoc.documentElement();
        xmlElement = xmlDoc.createElement('FirstElement');
        xmlElement.setAttribute('xmlns:xsi',ns);
        rootNode = xmlDoc.appendChild(xmlElement);

        //Child node 1
        xmlElement = xmlDoc.createElement('SecondElement');
        xmlElement.setAttribute2('type', ns, 'Attribute');
        Node1 = rootNode.appendChild(xmlElement);

        //Child node 2
        xmlElement = xmlDoc.createElement('ThirdElement');
        xmlElement.setAttribute2('type', ns, 'Attribute');
        Node2 = rootNode.appendChild(xmlElement);

        
        //Remove all child nodes
        rootNode.removeAll();

        // Save the file
        xmldoc.save('C:\\Altitudo\\test.xml');

    }

}

This will be the final result. As you see FirstElement’s child nodes have been deleted

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 )

Connecting to %s