Saturday, March 10, 2012

Iterate XML file in X++/Axapta

XML file is a very common method of interaction when we are dealing with any kind of third party software. We can create the XML file in X++ and send it as parameters to the third party software. In case, when we receive the XML file as output from the external software, there can be various challenges in parsing the XML file but the very first step in the process is to traverse the XML source file and extract the values. Below is the code to iterate the XML file in X++:
static void XMLIteratorTest(Args _args)
{
    str                 sourceXMLFile, sNumber, sName, sClass;
    XmlDocument         xmlDocument;
    XmlNodeList         nodeList;
    XmlNode             node;
    XMLNodeListIterator xmlNodeListIterator;
    Counter             counter;
    ;
    sourceXMLFile = "<SCHOOL>" +
                        "<STUDENT>" +
                            "<NUMBER>001</NUMBER>" +
                            "<NAME>Stud_A</NAME>" +
                            "<CLASS>8</CLASS>" +
                        "</STUDENT>" +
                        "<STUDENT>" +
                            "<NUMBER>002</NUMBER>" +
                            "<NAME>Stud_B</NAME>" +
                            "<CLASS>9</CLASS>" +
                        "</STUDENT>" +
                        "<STUDENT>" +
                            "<NUMBER>003</NUMBER>" +
                            "<NAME>Stud_C</NAME>" +
                            "<CLASS>7</CLASS>" +
                        "</STUDENT>" +
                    "</SCHOOL>";

    xmlDocument = XmlDocument::newXml(sourceXMLFile);
    nodeList = xmlDocument.selectNodes('//STUDENT');

    xmlNodeListIterator = new xmlNodeListIterator(nodeList);
    while(xmlNodeListIterator.moreValues())
    {
        counter++;
        node = xmlNodeListIterator.value();

        if(node.selectSingleNode('NUMBER'))
            sNumber = node.selectSingleNode('NUMBER').text();
        if(node.selectSingleNode('NAME'))
            sName = node.selectSingleNode('NAME').text();
        if(node.selectSingleNode('CLASS'))
            sClass = node.selectSingleNode('CLASS').text();
       
        info(strFmt("Record %1: Number - %2, Name - %3, Class - %4",
                        counter,
                        sNumber,
                        sName,
                        sClass));
        xmlNodeListIterator.nextValue();
    }
}

Output should look like this:
Record 1: Number - 001, Name - Stud_A, Class – 8
Record 2: Number - 002, Name - Stud_B, Class – 9
Record 3: Number - 003, Name - Stud_C, Class - 7

1 comment: