Importing data from an XML file
In Dynamics AX, XML file importing is done in a very similar way as exporting. In this recipe, we will continue using the System.XML
wrapper application classes. We will create a new class which reads XML files and displays the content onscreen. As a source file, we will use the previously created accounts.xml
file.
How to do it...
Carry out the following steps in order to complete this recipe:
1. Open the AOT, and create a new class named
ReadXmlFile
with the following code. Use the document created in the previous recipe:class ReadXmlFile { } public static void main(Args _args) { XmlDocument doc; XmlNodeList data; XmlElement nodeTable; XmlElement nodeAccount; XmlElement nodeName; #define.filename(@'C:\Temp\accounts.xml') doc = XmlDocument::newFile(#filename); data = doc.selectNodes('//'+tableStr(MainAccount)); nodeTable = data.nextNode(); while (nodeTable) { nodeAccount = nodeTable.selectSingleNode( fieldStr(MainAccount, MainAccountId)); nodeName = nodeTable.selectSingleNode( fieldStr(MainAccount, Name)); info(strFmt( "%1 - %2", nodeAccount.text(), nodeName.text())); nodeTable = data.nextNode(); } }
2. Run the class. The Infolog should display the contents of the
accounts.xml
file on the screen:
How it works...
In this recipe, we first create a new XmlDocument
. We create it from the file and hence we have to use its newFile()
method. Then we get all the document nodes of the table as XmlNodeList
. We also get its first element by calling the nextNode()
method.
Next, we loop through all the list elements and do the following:
1. Get an account number node as an
XmlElement
.2. Get an account name node as an
XmlElement
.3. Display the text of both nodes in the Infolog.
4. Get the next list element.
In this way, we retrieve the data from the XML file. A similar approach could be used to read any other XML file.