Sorting elements

When the source document contains a list of items that are not arranged in any order, but need to be output in alphabetical or numerical order, it is possible to sort these items. The Sort element is used within the Apply Templates element to sort the elements it selects:

<list>
  <item>Zimbabwe</item>
  <item>Morocco</item>
  <item>Zaire</item>
  <item>Algeria</item>
</list>
<template match="list">
  ... <apply-templates><sort/></apply-templates> ...
</template>


   Algeria
   Morocco
   Zaire
   Zimbabwe

Note that, contrary to the impression given by earlier examples, the Apply Templates element is not always an empty element, and other scenarios covered later also require this element to be present as a container element.

Basic sorting

In the simple default form shown above, the sort key is the content of the child elements. The item 'Algeria' will therefore appear first in the output document. By adding a Select attribute to the Sort element, it is possible to be more explicit. For example, the Item element may contain an attribute which is to serve as the sort key:

   <list>
     <item sortcode="Z">...</item>
     <item sortcode="M">...</item>
     <item sortcode="A">...</item>
   </list>


<sort select="@sortcode"/>

Secondary sorting

It is possible to create secondary sort keys simply by adding more Sort elements. The second occurrence of the Sort element indicates a sub-key. For example, a list of names may need to be sorted by last name, then, within each group, by first name as well:

<template...>
  <sort select="secondName"/>
  <sort select="firstName"/>
</template>


   Bergman, Ingmar
   Bergman, Ingrid
   ...
   Monroe, James
   Monroe, Marilyn

Sort options

Sorting order is also affected by the optional Order attribute, which takes a value of 'ascending' (the default) or 'descending', and possibly also by the Lang attribute, which identifies the language of the text.

In addition, the Data Type attribute, which has a default value of 'text', can be given a value of 'number', specifying that the items should be sorted by numeric value. For example, '12' would normally appear before '7', because the first digit of '12' has a lower ASCII value than '7', but in number mode '7' is obviously a smaller value than '12', so appears first.

Finally, the Case Order attribute specifies whether 'a' appears before 'A' ('lower-first') or the other way around ('upper-first').

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

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