In addition to the good advice given in many of the previous answers, let me add the following.
One can often find examples of beautiful XSLT code, especially when XSLT is used as a functional programming language.
For examples see this article on FXSL 2.0 -- the Functional Programming library for XSLT 2.0.
As an FP language XSLT is also a declarative language. This, among other things means that one declares, specifies existing relationships.
Such a definition often does not need any additional code to produce a result -- it itself is its own implementation, or an executable definition or executable specification.
Here is a small example.
This XPath 2.0 expression defines the "Maximum Prime Factor of a natural number":
if(f:isPrime($pNum))
then $pNum
else
for $vEnd in xs:integer(floor(f:sqrt($pNum, 0.1E0))),
$vDiv1 in (2 to $vEnd)[$pNum mod . = 0][1],
$vDiv2 in $pNum idiv $vDiv1
return
max((f:maxPrimeFactor($vDiv1),f:maxPrimeFactor($vDiv2)))
To pronounce it in English, the maximum prime factor of a number pNum
is the number itself, if pNum
is prime, otherwise if vDiv1
and vDiv2
are two factors of pNum
, then the maximum prime factor of pNum
is the bigger of the maximum prime factors of vDiv1
and vDiv2
.
How do we use this to actually calculate the Maximum Prime Factor in XSLT? We simply wrap up the definition above in an <xsl:function>
and ... get the result!
<xsl:function name="f:maxPrimeFactor" as="xs:integer">
<xsl:param name="pNum" as="xs:integer"/>
<xsl:sequence select=
"if(f:isPrime($pNum))
then $pNum
else
for $vEnd in xs:integer(floor(f:sqrt($pNum, 0.1E0))),
$vDiv1 in (2 to $vEnd)[$pNum mod . = 0][1],
$vDiv2 in $pNum idiv $vDiv1
return
max((f:maxPrimeFactor($vDiv1),f:maxPrimeFactor($vDiv2)))
"/>
</xsl:function>
We can, then, calculate the MPF for any natural number, for example:
f:maxPrimeFactor(600851475143)
= 6857
As for efficiency, well, this transformation takes just 0.109 sec.
Other examples of both ellegant and efficient XSLT code: