Using XPaths to set variable values in XSLT transforms for Dynamics AX

Using XPaths to set variable values in XSLT transforms for Dynamics AX

Using variables in XSLTs is often confusing for developers because they behave more like constants in other languages. You cannot change the value of a variable, and they can only be called within the scope of their declaration. When a value occurring in a descendant node determines the transform behavior at higher levels of the XML, XPaths can be utilized to set variable values based on the descendant XML nodes.

For Example, say we regularly send XMLs out of AX consisting of employee names and addresses for a various physical locations of company ABC.  Each XML is unique to exactly one physical location of the company. The program receiving the XML requires that the very first node of the XML provides information indicating that the incoming XML is for an international or domestic location. Therefore, we want change the very first node name from “Envelope” to either “International” or “Domestic” depending on the country provided for the company location (highlighted).

Visual 1

 

For the given XML, we can use a simple XPath to find the country value at the very beginning of the stylesheet. The XPath needs to include any relevant attributes and name spaces for all nodes. This XML has 2 namespaces signified with “xmlns.” We will call them Message=”http://schemas.microsoft.com/dynamics/2011/01/documents/Message” and Company=”http://schemas.microsoft.com/dynamics/2008/01/documents/Company” in the XSLT. The only attribute on the above XML is the name on the Company node. For each node, the general XPath format is “NameSpace:NodeName[@Attribute=’AttributeValue’].” If a node does not have a namespace or an attribute, then those parts should be left off. The “/” is used to separate parent and child nodes.

Therefore, the complete XPath to the country node is Message:Envelope/Message:Body/Message:MessageParts/Company:Company[@name=’ABC’]/Company:Location/Company:Country.

Now, all that’s left is to use our XPath in the context of an XSLT. There is more than one way to write an XSLT to perform the above transform on the given XML.
Here is one option:

Visual 2

Note that since the template matches on Message:Envelope, that node is not included in the XPath. The variable “country” is declared under the <xsl:template match=”Message:Envelope”> node, so it can only be called from within that template.

Share on Google+Tweet about this on TwitterShare on LinkedInShare on FacebookEmail this to someone