Anirudh
Anirudh

Reputation: 2247

Capitalize Element Name in XSL

I am writing a XSL transformation and my source has an element like this - "title". The target xml should contain "Title". Is there a way to capitalize the first letter of a string in XSL?

Upvotes: 3

Views: 8555

Answers (4)

Laurent CAPRANI
Laurent CAPRANI

Reputation: 139

Here is a pure XLST1 template that creates CamelCase names from ASCII sentences.

<xsl:template name="Capitalize">
    <xsl:param name="word" select="''"/>
    <xsl:value-of select="concat(
        translate(substring($word, 1, 1),
            'abcdefghijklmnopqrstuvwxyz',
            'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
        translate(substring($word, 2),
            'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'abcdefghijklmnopqrstuvwxyz'))"/>
</xsl:template>
<xsl:template name="CamelCase-recursion">
    <xsl:param name="sentence" select="''"/>
    <xsl:if test="$sentence != ''">
        <xsl:call-template name="Capitalize">
            <xsl:with-param name="word" select="substring-before(concat($sentence, ' '), ' ')"/>
        </xsl:call-template>
        <xsl:call-template name="CamelCase-recursion">
            <xsl:with-param name="sentence" select="substring-after($sentence, ' ')"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>
<xsl:template name="CamelCase">
    <xsl:param name="sentence" select="''"/>
    <xsl:call-template name="CamelCase-recursion">
        <xsl:with-param name="sentence" select="normalize-space(translate($sentence, &quot;:;,'()_&quot;, ' '))"/>
    </xsl:call-template>
</xsl:template>

Upvotes: 0

D&#233;m
D&#233;m

Reputation: 1

Cleaner: use an existing library: FunctX XSLT http://www.xsltfunctions.com/ There's a function capitalize-first() http://www.xsltfunctions.com/xsl/functx_capitalize-first.html

No need to reinvent the wheel in every XSLT, stick the lib somewhere and xsl:include it.

Upvotes: 2

Tim C
Tim C

Reputation: 70618

Following on from the Johannes said, to create a new element using xsl:element you would probably do something like this

<xsl:template match="*">
    <xsl:element name="{concat(upper-case(substring(name(), 1, 1)), substring(name(), 2))}">
        <xsl:value-of select="." />
    </xsl:element>
</xsl:template>

If your are using XSLT1.0, you won't be able to use the upper-case function. Instead, you will have to make-do with the cumbersome translate function

    <xsl:element name="{concat(translate(substring(name(), 1, 1), 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'), substring(name(), 2))}">

Upvotes: 8

Joey
Joey

Reputation: 354586

I guess you have to manually use <xsl:element> and then something like the following beast:

concat(upper-case(substring(name(), 1, 1)), substring(name(), 2))

Upvotes: 1

Related Questions