Reputation: 126
I am trying to get a sorted list of all the unique Locality elements from XML in the following structure
<EXPORT>
<ESTABLISHMENTS>
<ESTABLISHMENT>
<LOCATION>
<LOCALITY>LONDON W2</LOCALITY>
</LOCATION>
</ESTABLISHMENT>
<ESTABLISHMENT>
<LOCATION>
<LOCALITY>ABERDEEN</LOCALITY>
</LOCATION>
</ESTABLISHMENT>
<ESTABLISHMENT>
<LOCATION>
<LOCALITY>LONDON E12</LOCALITY>
</LOCATION>
</ESTABLISHMENT>
<ESTABLISHMENT>
<LOCATION>
<LOCALITY>LONDON E4</LOCALITY>
</LOCATION>
</ESTABLISHMENT>
<ESTABLISHMENT>
<LOCATION>
<LOCALITY>BIRMINGHAM</LOCALITY>
</LOCATION>
</ESTABLISHMENT>
<ESTABLISHMENT>
<LOCATION>
<LOCALITY>LONDON E1</LOCALITY>
</LOCATION>
</ESTABLISHMENT>
<ESTABLISHMENT>
<LOCATION>
<LOCALITY>LONDON E1</LOCALITY>
</LOCATION>
</ESTABLISHMENT>
</ESTABLISHMENTS>
</EXPORT>
Using the following XSLT I am able to get the unique localities in alpha sorted order.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:key name="establishment-by-locality" match="ESTABLISHMENTS/ESTABLISHMENT/LOCATION" use="LOCALITY"/>
<xsl:template match="EXPORT">
<xsl:for-each select="ESTABLISHMENTS/ESTABLISHMENT/LOCATION[count(.| key('establishment-by-locality', LOCALITY)[1]) = 1]">
<xsl:sort select="LOCALITY"/>
<xsl:element name="Locality">
<xsl:value-of select="LOCALITY"/>
</xsl:element>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
However, if possible I would like to sub-sort the London localities by their postcode (the suffix after the space), to provide the following order
<Locality>ABERDEEN</Locality>
<Locality>BIRMINGHAM</Locality>
<Locality>LONDON E1</Locality>
<Locality>LONDON E4</Locality>
<Locality>LONDON E12</Locality>
<Locality>LONDON W2</Locality>
Where actual results received are (note London E4)
<Locality>ABERDEEN</Locality>
<Locality>BIRMINGHAM</Locality>
<Locality>LONDON E1</Locality>
<Locality>LONDON E12</Locality>
<Locality>LONDON E4</Locality>
<Locality>LONDON W2</Locality>
Unfortunately, due to relying on the Locality element again I seem to be going around in circles.
Any assistance much appreciated.
Upvotes: 1
Views: 54
Reputation: 70618
There is no issue at all with using the same element in multiple sorts. Your actual problem is that "E12" and "E4" are being sorted alphabetically, when you want sort by the letter(s) first, then by the number.
This is quite a crude solution, but this could do it...
<xsl:sort select="substring-before(concat(LOCALITY, ' '), ' ')"/>
<xsl:sort select="translate(substring-after(LOCALITY, ' '), '0123456789', '')"/>
<xsl:sort select="translate(substring-after(LOCALITY, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '')" data-type="number" />
This will cope with area codes like NW10 too (i.e. more than one letter)
Upvotes: 2