Search code examples
xmlxslt

XSL - How do you capitalize first letter


I have following xml.

<Name>
  <First>john</First>
  <Last>smith</Last>
</Name>

I want to capitalize first letter and out put in following formate.

 <FullName>John Smith</FullName>

Thank you in advance.


Solution

  • I. XSLT 2.0 solution:

    <xsl:stylesheet version="2.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>
    
     <xsl:template match="/*">
      <FullName><xsl:apply-templates/></FullName>
     </xsl:template>
    
     <xsl:template match="First|Last">
      <xsl:sequence select=
      "concat(upper-case(substring(.,1,1)),
              substring(., 2),
              ' '[not(last())]
             )
      "/>
     </xsl:template>
    </xsl:stylesheet>
    

    when this transformation is applied on the provided XML document:

    <Name>
        <First>john</First>
        <Last>smith</Last>
    </Name>
    

    the wanted, correct result is produced:

    <FullName>John Smith</FullName>
    

    II. XSLT 1.0 solution:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>
    
     <xsl:variable name="vLower" select=
     "'abcdefghijklmnopqrstuvwxyz'"/>
    
     <xsl:variable name="vUpper" select=
     "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
    
     <xsl:template match="/*">
      <FullName><xsl:apply-templates/></FullName>
     </xsl:template>
    
     <xsl:template match="First|Last">
      <xsl:value-of select=
      "concat(translate(substring(.,1,1), $vLower, $vUpper),
              substring(., 2),
              substring(' ', 1 div not(position()=last()))
             )
      "/>
     </xsl:template>
    </xsl:stylesheet>