Importing data from an XML file

This is a part of previous post on reading and writing xml file from/to AX.

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 on screen. As a source file, we will use the previously created sales.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 ReadorWriteXml with the following code.
Use the document created in the previous post:
class ReadorWriteXml
{
}

public void readXMLFile()
{
XmlDocument doc;
XmlNodeList data;
XmlElement nodeTable;
XmlElement nodeId;
XmlElement nodeName;
XmlElement nodeCustAccount;
#define.filename(@’C:\Temp\sales.xml’)
doc = XmlDocument::newFile(#filename);
data = doc.selectNodes(‘//’+tableStr(SalesTable));
nodeTable = data.nextNode();
while (nodeTable)
{
nodeId = nodeTable.selectSingleNode(fieldStr(SalesTable, SalesId));
nodeName = nodeTable.selectSingleNode(fieldStr(SalesTable, SalesName));
nodeCustAccount = nodeTable.selectSingleNode(fieldStr(SalesTable, CustAccount));
info(strFmt(“%1 – %2 – %3”,nodeId.text(),nodeName.text(),nodeCustAccount.text()));
nodeTable = data.nextNode();
}
}
public static void main(Args args)
{
ReadorWriteXml file = new ReadorWriteXml();
file.readXMLFile();
}

2. Run the class. The Infolog should display the contents of the sales.xml file on the screen:

1

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 salesId node as an XmlElement.
2. Get salesname node as an XmlElement.
3. Get cust account as an XmlElement.
4. Display the text of nodes in the Infolog.
5. 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.

If you need xpo file of this, please specify your mail address in comment.

Hope you understood….
Till then, Happy DaXing…

Advertisements

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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: