Multiple sort criteria

The list of countries example above raises an interesting problem. Having decided to sort the countries by their population figures, what happens when two countries have the same population value? By default, they are simply output in document order. In the following example, Italy and the UK have the same count, and so the order in which they appear depends entirely on the order that they occur in the source file:

<countries>
  <country>
    <name>UK</name>
    <population>58</population>
  </country>
  <country>
    <name>Italy</name>
    <population>58</population>
  </country>
</countries>

It would probably be more desirable to sort countries with the same population count into alphabetical order, thus introducing a secondary sorting requirement. This can be achieved simply by repeating the Sort element in the template:

<xsl:template match="countries">
  <DIV>
    <xsl:apply-templates>
      <xsl:sort data-type="number"
                select="population"/>
      <xsl:sort select="name"/>
    </xsl:apply-templates>
  </DIV>
</xsl:template>


   <DIV>
     <P>Italy <B>58</B></P>
     <P>UK <B>58</B></P>
     ...
     <P>USA <B>262</B></P>
   </DIV>

The order in which the Sort elements appear is very important. The first occurrence is deemed to be the primary sort field. The secondary sort takes effect only on the items within each primary group.

There may, by the same principle, be more than two levels of sorting.

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

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