1

Is it possible to do, and how would one achieve, natural case sorting in XSL?

For instance, given the following XML snippet:

<items>
  <item>A 24</item>
  <item>B 12</item>
  <item>B 11</item>
  <item>C 10</item>
  <item>A 1</item>
  <item>B 2</item>
</item>

How could I sort the output so that I had a list of elements as below?

<ul>
  <li>A 1</li>
  <li>A 24</li>
  <li>B 2</li>
  <li>B 11</li>
  <li>B 12</li>
  <li>C 10</li>
</ul>

Edit: I'm particularly interested in solutions that can work with arbitrary strings, eg. ones that don't follow a common pattern, similar to the way PHP's natsort works.

Phillip B Oldham
  • 18,807
  • 20
  • 94
  • 134

1 Answers1

0

You can use multiple xsl:sorts:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/items">
    <ul>
      <xsl:apply-templates select="item">
        <xsl:sort select="substring-before(., ' ')" />
        <xsl:sort select="substring-after(., ' ')" data-type="number" />
      </xsl:apply-templates>
    </ul>
  </xsl:template>

  <xsl:template match="item">
    <li>
      <xsl:value-of select="."/>
    </li>
  </xsl:template>
</xsl:stylesheet>

When run on your sample input, this produces:

<ul>
  <li>A 1</li>
  <li>A 24</li>
  <li>B 2</li>
  <li>B 11</li>
  <li>B 12</li>
  <li>C 10</li>
</ul>

More thorough (generic) natural sorting requires a much more involved approach. Dimitre Novatchev has provided an XSLT 1.0 approach here on Stack Overflow, and another site seems to have an XSLT 2.0 approach. Both are too long to merit reproducing here, so please seek them at those links.

Community
  • 1
  • 1
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Is it possible to do this generically, eg. without splitting the string on a space? For instance, if I have a list of files: `200327582_RFTS, 138082008_RFTS, 138012009 RFTS, 10101010, ABCDEF`. – Phillip B Oldham Feb 05 '13 at 15:51
  • @unpluggd [Here](http://stackoverflow.com/a/8352114/1945651) is an SO answer by Dimitre Novatchev that appears to be an implementation with a few limitations. [This](http://www.mhonarc.org/archive/html/xsl-list/2011-03/msg00003.html) appears to be an XSLT 2.0 implementation. – JLRishe Feb 05 '13 at 16:30