Fork me on GitHub

Read XML string (elements, attributes, texts) [AX2012]

An X++ example of getting the data from a bit more complex XML string.

Here you can find a tutorial on making XML string in X++.

Solution (this time only a single Job)

static void readXMLString(Args _args)
    // Define XML Document and its nodes
    XmlDocument     doc;
    XmlNodeList     xmlScriptList;
    XmlNodeList     xmlProjectList;
    XmlElement      nodeScript;
    XmlElement      nodeProject;
    XmlElement      nodeNote;
    XMLParseError   xmlError;
    // Define temporary variables
    str _xmlMsg;
    int i, j;


    // XML string to read
    _xmlMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><XMLScript Version=\"2.0\"><Project Name=\"Holidays\"><Format>C:\NotesDesign\Note.jpg</Format><PrintSetup><Printer>PDFPrinter</Printer></PrintSetup><Note Date=\"2014/12/10\" ID=\"N001\"><To>Tim</To><Body>Make sure all tasks are completed before holidays!</Body></Note><Note Date=\"01/01/2015\" ID=\"N002\"><To>Sophie</To><Body>Don't forget your Christmas shopping this weekend!</Body></Note></Project></XMLScript>";

    // Create the XML Document
    doc = new XmlDocument();

    // Verify XML Document Structure
    xmlError  = doc.parseError();
    if(xmlError && xmlError.errorCode() != 0)
        throw error(strFmt("XML Error: %1", xmlError.reason()));

    // Get the root element and its child nodes
    nodeScript = doc.getNamedElement("XMLScript");
    xmlScriptList = nodeScript.childNodes();

    for(i=0; i < xmlScriptList.length(); i++)
        nodeProject = xmlScriptList.item(i);
        xmlProjectList = nodeProject.childNodes();

        info("### Project information: ");

        // Print out node and attribute values
        info(strFmt("XML Document Version: %1", nodeScript.getAttribute("Version")));
        info(strFmt("Project Name: %1", nodeProject.getAttribute("Name")));
        info(strFmt("Format: %1", nodeProject.getNamedElement("Format").text()));
        info(strFmt("PrintSetup (innerXML): %1", nodeProject.getNamedElement("PrintSetup").innerXml()));
        info(strFmt("Printer (text): %1 OR Printer (innerText): %2", 

        // Loop through the repeating nodes
        info("### Notes: ");       
        for (j=2; j < xmlProjectList.length(); j++)
            nodeNote = xmlProjectList.item(j);

            info(strFmt("ID: %1, Date: %2", nodeNote.getAttribute("ID"), nodeNote.getAttribute("Date")));
            info(strFmt("To: %1", nodeNote.getNamedElement("To").text()));
            info(strFmt("Body: %1", nodeNote.getNamedElement("Body").text()));

Infolog output

XML Data

Comments !