Selective sorting

The examples above all assume that the sort order value is the entire content of the elements to be sorted. The Select attribute can be used to identify a more specific item to be used as the sort value. The implied value of this attribute is '.', indicating the current element. The following examples are equivalent:

<sort/>


<sort select="."/>

The current element, in this context, means the element being sorted, and it applies to each one of these elements in turn.

As usual, this attribute can take any XPath expression, greatly improving the flexibility of the sort feature.

Child element selection

Elements that contain other elements can be sorted, and the sorting criteria can be specified to be the content of one of the sub-elements. In the following example, a list of countries consists of a name and population count (in millions) for each country. One interesting way to organize this list is to sort it by population size:

<countries>
  <country>
    <name>USA</name>
    <population>262</population>
  </country>
  <country>
    <name>UK</name>
    <population>58</population>
  </country>
</countries>


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


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

Attribute selection

Because the Select attribute can take any expression, it can be used to target an attribute instead of an element. For example, if the Country element has a Population attribute instead of an element, this attribute can be specified:

<sort data-type="number" select="@population" />


   <countries>
     <country population="262">
       <name>USA</name>
     </country>
     <country population="58">
       <name>UK</name>
     </country>
   </countries>

Again, when deciding on the expression needed, it is important to recall that the current element is the element being sorted (in this case, each Country element), not the element from which the sort is specified (Countries).

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

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