xmlxsltxslt-1.0title-case

Convert First character of each word to upper case


I have a String and I need to convert the first letter of each word to upper case and rest to lower case using xsl, For example,

Input String= dInEsh sAchdeV kApil Muk

Desired Output String= Dinesh Sachdev Kapil Muk

Although, I know I have to use translate function for the purpose but how can I translate the first charter of each word to Upper-case and rest all in lower- case using XSLT 1.0

Thanks


Solution

  • The following is not "nice", and I'm sure somebody (mainly Dimitri) could come up with something far simpler (especially in XSLT 2.0)... but I've tested this and it works

    <xsl:template name="CamelCase">
      <xsl:param name="text"/>
      <xsl:choose>
        <xsl:when test="contains($text,' ')">
          <xsl:call-template name="CamelCaseWord">
            <xsl:with-param name="text" select="substring-before($text,' ')"/>
          </xsl:call-template>
          <xsl:text> </xsl:text>
          <xsl:call-template name="CamelCase">
            <xsl:with-param name="text" select="substring-after($text,' ')"/>
          </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
          <xsl:call-template name="CamelCaseWord">
            <xsl:with-param name="text" select="$text"/>
          </xsl:call-template>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:template>
    
    <xsl:template name="CamelCaseWord">
      <xsl:param name="text"/>
      <xsl:value-of select="translate(substring($text,1,1),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" /><xsl:value-of select="translate(substring($text,2,string-length($text)-1),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')" />
    </xsl:template>
    

    The basic idea is that you call CamelCase, if it find a space, then it runs CamelCaseWord on everything before the space (i.e. the first word) and then calls CamelCase again with the everything after the space (i.e. the rest of the sentence). Otherwise if no space is found (because it's got to the last word in the sentence), then it just calls CamelCaseWord.

    The CamelCaseWord template simply translates the first character from lower to upper (if necessary) and all remaining characters from upper to lower (if necessary).

    So to call it you'd have...

    <xsl:call-template name="CamelCase">
       <xsl:with-param name="text">dInEsh sAchdeV kApil Muk</xsl:with-param>
    </xsl:call-template>