Is there any way to optimize this code.
<xsl:choose>
<xsl:when test="val1 = val2">
<xsl:apply-templates select="node"/>
</xsl:when>
<xsl:otherwise>
<div>
<xsl:apply-templates select="node"/>
</div>
</xsl:otherwise>
</xsl:choose>
I do not like having to write twice the same <xsl:apply-templates select="node"/>.
Update:
The idea is that depending on the result of comparison to do one of two things:
-
Just print some information (which we obtain after applying the template
<xsl:apply-templates select="node"/>). -
Print the same information, but in advance “wrapping” it in the container (
divfor example).
Use:
Here is a complete example. This transformation:
when applied on this XML document:
produces the wanted, correct result:
Explanation of the solution:
Whenever an
<xsl:apply-templates>has an<xsl:sort>child, the nodes that are selected are sorted according the data provided in the<xsl:sort>child(ren) and the results of applying templates on each selected node appear in the output in that (sort) order — not in document order.In the transformation above we have:
This means that the results of applying templates to the elements named
nodefor which it is true thatval1=val2will appear before the results of applying templates to the elements namednodefor whichval1=val2is not true. This is becausefalsesorts beforetrue.If this explanation is not clear, the reader is directed to read more about
<xsl:sort>.