AJP
AJP

Reputation: 2125

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.

Upvotes: 20

Views: 26448

Answers (3)

Antonio Petrocelli
Antonio Petrocelli

Reputation: 1

concat( upper-case(substring($Name,1,1)), substring($Name,2,string-length($Name)) )

Upvotes: -2

Suresh
Suresh

Reputation: 59

Try:

concat(
  translate(
    substring($Name, 1, 1),
    'abcdefghijklmnopqrstuvwxyz',
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  ),
  substring($Name,2,string-length($Name)-1)
)

Upvotes: 0

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243479

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>

Upvotes: 36

Related Questions