The Infolog

A blog of Dynamics AX development tips and tricks

Skip to: Content | Sidebar | Footer

Navigating XML with X++

29 September, 2013 (13:30) | Dynamics AX | By: Howard Webb

About a year ago I had the luxury of some self learning time at work. I set about a task to intergrate a mapping utility with route planning. I chose Google maps as it returned an XML file that was easy to read.

I wanted to pick up the total distance and time for my Google maps mod. You can use Google’s API to get an XML file returned by passing it a dynamic URL (an example is attached). Within that you have the total distance and time and the status of the request (for use with exception handling). Most of the AX books I have do not have great examples of getting values from an XML file. They seem to concentrate on alliterating through a few child nodes to populate a table and not getting values directly. They use code lines such as:

Doc.selectNodes(‘//’+tablestr(LedgerTable));

I did a Google for examples of picking up a single value from within an XML file and could not find too much so I looked in to it. All examples I have found use the following to select a node from within an XML file:

Doc.selectSingleNode(‘//NodeName’);

However I found that this will only work if the node name is unique as it will select the first occurrence of the node name if not. I had thought this to be an issue and that AX should respect where in the XML file you were operating. Not knowing better I wrote a few lines of code to loop through the entire XML file to get the node I actually wanted. However a co-worker kindly pointed me down the path towards an XPath solution.

For those not within the know XPath is a query language used by lots of programs to allow selecting of areas/nodes from within an XML file. If you’ve ever done anything with XML files within AX you’ll have noticed something like this:

xpath

 

If you look at the W3C webpage the method was performing as expected, a double / before a node name should “Select nodes in the document from the current node that match the selection no matter where they are” and using single node was just returning the first example it found. The solution to the problem was to use the full XPath. After a few issues I have discovered that you need the whole path and do not need a double slash.

As an example in that file the line:

info(doc.selectSingleNode(‘/route/leg/distance/text’).text());

Will return “288 km” – the total distance for the journey

More can be found on Xpath here:

http://en.wikipedia.org/wiki/XPath

http://www.w3schools.com/xpath/xpath_syntax.asp

and I’d suggest that you use the XML tools plugin for NotePad ++ which can pick up the XPath for you from a file.

 

Print Friendly, PDF & Email

Write a comment