Sorting on Calculated Variables
The sorting performed by the <xsl:sort>
elements above, in prodsort.xsl, would be suitable for an application like a catalog, in which a given product needs to be located easily.
Suppose, though, that the corporation's chief financial officer asks to see a list of all products, arranged in order by retail price. The first problem this presents is that our data contains a mixture prices in various currency denominations: US dollars (curr="USD"
), Euros (curr="EU"
), and British pounds Sterling (curr="GBP"
). This might seem like an easy problem to fix. You could define a variable, such as usd_equiv
, which would hold the retail price of the product, converted to its US dollar equivalent. Then, you might think, you could sort on the usd_equiv
variable, instead of sorting directly on the value of the <price>
element.
The problem is that you cannot sort directly on a variable. The sort key used as the value of the <xsl:sort>
element's select
attribute must be an XPath expression of some kind.
You can, however, sort on a calculated value, using the following general steps:
- Clone the source tree into a variable, which will then hold a result tree fragment. For more information, see Introduction to Result Tree Fragments.
- Create a new element to hold the calculated result, and append this new element to the cloned source tree created in step 1.
- Select and sort the result tree fragment created by steps 1 and 2. Do not select and sort the original source tree. Note that this will require the result tree fragment to be converted to a node-set, using the
msxsl:node-set()
function. For more information, see Using msxsl:node-set() to Process Result-Tree Fragments.
The remainder of this topic works through each of these steps for the prodsort example. The complete solution to the problem stated above, the prodsort_curr.xsl style sheet, is available at Sample XSLT File for Sorting.
The solution to this problem requires the following steps.
- Step 1: Cloning the Source Tree
- Step 2: Creating the New Element
- Step 3: Sorting the Source Tree Clone