XSL Best Practices
While modifying the default XSLs shipped for customization, follow the best practices for writing XSL. Instead of evaluating the same node-set more than once, save it in a variable.
- Where there's a need to iterate over a set of nodes, and for each node, lookup or
access other nodes, using XSLT Key can greatly optimize transformation. This
approach avoids the inefficiency of repeated traversal and avoids the
O(n2) problem. Else, each node requires O(n) search through all other
nodes, leading to quadratic performance issue.
- Define an XSL Key as
<xsl:key name="name" match="match" use="use"/>
- name: The name of the key.
- match: The XPath expression that selects the nodes to be indexed.
- use: The XPath expression that defines the value to index by (value to search on).
- Use the key with key (name, search) function to quickly find nodes that match a particular search value.
- Define an XSL Key as
Example: To find the manager’s name of an employee:
<employees>
<employee><id>1</id><name>John</name><managerId>2</managerId></employee>
<employee><id>2</id><name>Jack</name></employee>
<employee><id>3</id><name>Richard</name><managerId>1</managerId></employee>
</employees>
- Defining the Key:
<xsl:key name=”employeeById” match=”employee” use=”id” />
- Usage:
<xsl:variable name=”managerId”><xsl:value-of select=”key(‘employeeById’, 1)/managerId” /></xsl:variable>
<ManagerName><xsl:value-of select =”key(‘employeeById’, $managerId)/name”/></ManagerName>