Thursday, February 17, 2011

Identity template in XSLT

Identity template in XSLT

Identity template is used to copy everything from the source to the destination. It demonstrates the charm of the recursion ability of XSLT. The below is the basic form of the identity template. 

Figure 1. Identity template
How does it work?

1. Firstly by using match=”@* node()” the template will be used for each attribute and each node which include element node, text node, comment and processing-instruction. But the namespace node is not included here.

2. Then for each matched node (attribute, element, text node or whatever) do the copy.

3. Finally inside apply the template recursively to child elements if the node has any. This will show the charm of XSLT’s recursive ability which makes the XSLT template very clean and powerful.

However that is just the basic form of the identity template. In the reality there seems no chance to make the exact copy from the source to destination. Quite often some modifications are required while doing the copy. For example a portion of XML needs to be copied but at the same time the value of one particular element is needed to be assigned a new value or a new attribute is needed to add to this particular element.

These variations to the basic form of XSLT identity template can be achieved via another template which works together with identity template. This template will handle the copy of one particular element or attribute. The key point is that this template has the specific match than the identity template and when one element or attribute matches this template, XSLT engine will choose this template to process the element or attribute instead of identity template although the element or attribute also matches the identity template. Why? Because the identity template is less specific.


This example is quite simple and it just copies everything from the source to the target except the value of one element. 

Figure 2. Source

Figure 3. Transformation

Figure 4. Result

This example is a bit complicated than example 1.  What we need to do is to convert one root element from one name to another name and at the same time change the namespace XYZ to ABC.  All subelements keep the same name.     
 Figure 5. Source

 Figure 6. Transformation

 Figure 7. Result

No comments:

Post a Comment