Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSL - How do you capitalize first letter

Tags:

xml

xslt

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.

like image 618
AJP Avatar asked Mar 08 '12 01:03

AJP


1 Answers

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>
like image 118
Dimitre Novatchev Avatar answered Oct 15 '22 13:10

Dimitre Novatchev