XSLT snippet to convert string from hyphens to CamelCase

Here is a snippet to convert string in XSLT template from hyphenized text to CamelCase. (Developed today while creating new import/export templates for Doctrine2 YAML support).

Usage:

First:
		<xsl:call-template name="ConvertXmlStyleToCamelCase">
			<xsl:with-param name="text">orm-designer</xsl:with-param>
		</xsl:call-template>

Second:
		<xsl:call-template name="ConvertXmlStyleToCamelCase">
			<xsl:with-param name="text">orm-designer</xsl:with-param>
			<xsl:with-param name="firstLower" select="false()"/>
		</xsl:call-template>

Result:

First: ormDesigner
Second: OrmDesinger

XSLT Template:

	<!-- =========================================================================== -->
	<!-- === Convert camel-case-text to CameCaseText                             === -->
	<!-- === (c) Inventic s.r.o. ORM Designer team (http://www.orm-designer.com) === -->
	<!-- =========================================================================== -->
	<xsl:template name="ConvertXmlStyleToCamelCase">
		<xsl:param name="text"/>
		<xsl:param name="firstLower" select="true()"/>

		<xsl:variable name="Upper">ABCDEFGHIJKLMNOPQRSTUVQXYZ</xsl:variable>
		<xsl:variable name="Lower">abcdefghijklmnopqrstuvwxyz</xsl:variable>

		<xsl:for-each select="str:split($text,'-')">
			<xsl:choose>
				<xsl:when test="position()=1 and $firstLower = true()">
					<xsl:value-of select="substring(node(),1,1)"/>
				</xsl:when>
				<xsl:otherwise>
					<xsl:value-of select="translate(substring(node(),1,1),$Lower,$Upper)"/>
				</xsl:otherwise>
			</xsl:choose>
			<xsl:value-of select="substring(node(),2,string-length(node()))"/>
		</xsl:for-each>
	</xsl:template>

Feel free to use in whatever way you find it useful.

Leave a Reply

Your email address will not be published. Required fields are marked *