xsl-list
[Top] [All Lists]

[xsl] Sorting using helper structure, position(), xsl:key

2008-04-10 06:10:11
I'm not clear as to what's possible and what's not. I have a
set of items I want to sort based on the category (@cat) they
are assigned to. The items look like this:

  <Item cat="film">some data</Item>

There a couple of ways to solve this, like mapping the values
of @cat (which don't naturally sort into the right order) to
another set of values, or adapting the value of @cat itself so
it naturally sorts into the correct order (which is inflexible).

First question: Is it possible, in XSLT 1.0, to sort my items
based on a helper structure like the following, where the
target order is specified by the (document) order of the <Cat>
element nodes - as opposed to, say, an attribute explicitly
providing the sort key, as in <Cat pos="1">film</Cat> ?

  <Categories>
    <Cat>film</Cat>
    <Cat>spor</Cat>
    <Cat>kult</Cat>
    <Cat>info</Cat>
    <Cat>kind</Cat>
  </Categories>

My idea is that as the position() function returns the context
position, it may somehow be possible to put that function to use
here. So - second question - is it? If so, how would I do it?

Or - third question - do I have to transform this structure
adding a @pos attribute (which yields <Cat pos="1">film</Cat>
etc), capture it into an RTF variable and then use that RTF to
look up my sort key?

  <xsl:template match="Cat"><!-- add @pos to Cat -->
    <xsl:copy>
      <xsl:attribute name="pos">
        <xsl:value-of select="position()"/>
      </xsl:attribute>
      <xsl:value-of select="."/>
    </xsl:copy>
  </xsl:template>

  <xsl:variable name="m-RTF"><!-- build RTF -->
    <Map>
      <xsl:apply-templates select="/*/Categories/Cat"/>
    </Map>
  </xsl:variable>

  <!-- convert to node-set for convenience -->
  <xsl:variable name="m" select="exsl:node-set($m-RTF)"/>

  <!-- access value -->
  <xsl:value-of select="$m/*/Cat[ . = 'kind']/@pos"/>

Finally, for a huge set of categories, I'd want to use an
xsl:key. How would that fit into the picture? Is it possible
to have the key return the context position? Or would this be
difficult as maybe there is no context when an xsl:key is
built?

Michael

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--