Re: [xsl] monthNumber from monthName

Subject: Re: [xsl] monthNumber from monthName
From: Graydon <graydon@xxxxxxxxx>
Date: Sat, 21 Jan 2012 14:13:14 -0500
On Sat, Jan 21, 2012 at 06:43:57PM +0000, James Cummings scripsit:
[snip]
> <xsl:function name="jc:getMonth" as="xs:string"><xsl:param name="month"/>
>     <xsl:choose>
>         <xsl:when test="$month='january'">01</xsl:when>
>         <xsl:when test="$month='february'">02</xsl:when>
>         <xsl:when test="$month='march'">03</xsl:when>
>         <xsl:when test="$month='april'">04</xsl:when>
>         <xsl:when test="$month='may'">05</xsl:when>
>         <xsl:when test="$month='june'">06</xsl:when>
>         <xsl:when test="$month='july'">07</xsl:when>
>         <xsl:when test="$month='august'">08</xsl:when>
>         <xsl:when test="$month='september'">09</xsl:when>
>         <xsl:when test="$month='october'">10</xsl:when>
>         <xsl:when test="$month='november'">11</xsl:when>
>         <xsl:when test="$month='november'">12</xsl:when>
>         <xsl:otherwise>00</xsl:otherwise>
>     </xsl:choose></xsl:function>
> 
> 
> But in the back of my head, since the result is just a leading-zero
> sequence number in a potential list of values.... I can't help
> thinking there is a better way to do this.

<xsl:function as="xs:string" name="d:getMonthName">
   <xsl:param name="monthName"/>
   <xsl:variable name="monthNames"
       select="('january','february','march','april','may','june','july','august','september','october','november','december')"/>
   <xsl:sequence
       select="format-number(if (index-of($monthNames,$monthName) castable as xs:integer) 
                           then index-of($monthNames,$monthName) 
                           else 0,'00')"
   />
</xsl:function>

This is insanely fragile unless you have strict checking to enforce case,
spelling, and language of month names.

If you're in a situation where you're going to get January, jan., jan, Janvier,
etc. you can take your original version and add tests, which has the advantage
of simplicity and ease of maintenance, or you can stuff all those tests into a
returnMonthName function, which has the advantage of abstraction and
compactness of expression.  But either way this sort of thing with
unconstrained string data month names is a pain.

-- Graydon

Current Thread