Looping and Sorting
As shown throughout this chapter, you can use
<xsl:apply-templates ...>
to search for
patterns in an XML document. This type of processing is sometimes
referred to as a "
data driven” approach because the
data of the XML file drives the selection process. Another style of
XSLT programming is called "template driven,” which
means that the template’s code tends to drive the selection
process.
Looping with <xsl:for-each>
Sometimes it is convenient to explicitly drive the selection process
with an
<xsl:for-each>
element, which is
reminiscent of traditional programming techniques. In this approach,
you explicitly loop over a collection of nodes without instantiating
a separate template as <xsl:apply-templates>
does. The syntax for <xsl:for-each>
is as
follows:
<xsl:for-each select="president"> ...content for each president element </xsl:for-each>
The select
attribute can contain any XPath
location path, and the loop will iterate over each element in the
resulting node set. In this example, the context is
<president>
for all content within the loop.
Nested loops are possible and could be used to loop over the list of
<vicePresident>
elements.
Sorting
Sorting can be
applied in either a data-driven or template-driven approach. In
either case,
<xsl:sort>
is added
as a child element to something else. By adding several consecutive
<xsl:sort>
elements, you can accomplish multifield sorting. Each sort can be in ascending or descending order, and the data type for sorting ...
Get Java and XSLT now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.