Simple element sorting

One good example of the need to sort elements is the task of creating a glossary. In the following example, the Glossary element contains a number of Item elements, which have not been arranged in any particular order:

<glossary>
  <item>XSL - ...</item>
  <item>XML - ...</item>
  <item>SGML - ...</item>
  <item>HTML - ...</item>
</glossary>

Using techniques described previously, it would be possible to convert this data into an equivalent HTML structure. However, as elements are normally processed in document order, the output shown below is in the same order as the source XML items:

<DIV>
  <P>XSL - ...</P>
  <P>XML - ...</P>
  <P>SGML - ...</P>
  <P>HTML - ...</P>
</DIV>

The Sort element can be used to override this default ordering. It is placed within the Apply Templates element, where it specifies that the elements matched by this instruction are to be output in sorted order. In the following example, the template for the Glossary element includes the Sort element, indicating that the Item elements embedded within the Glossary element are to be sorted:

<xsl:template match="glossary">
  <DIV>
    <xsl:apply-templates>
      <xsl:sort/>
    </xsl:apply-templates>
  </DIV>
</xsl:template>

<xsl:template match="item">
  <P><xsl:apply-templates/></P>
</xsl:template>

The Item elements are therefore transformed into paragraph elements that are output in the following order:

<DIV>
  <P>HTML - ...</P>
  <P>SGML - ...</P>
  <P>XML - ...</P>
  <P>XSL - ...</P>
</DIV>

Note that the Sort element can also be used in the For Each element (see Chapter 16). When it is used here, it must be the first element to appear:

<template match="addresses">
  <for-each ...>
      <sort ...>
      ...
  </for-each>
</template>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset