XSLT snippet to convert string from CamelCase to hyphens (Hyphenize)

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

Usage:

<xsl:call-template name="ConvertCamelToXmlStyle">
	<xsl:with-param name="text">OrmDesigner</xsl:with-param>
</xsl:call-template>

Result:

orm-designer

XSLT Template:

	<!-- =========================================================================== -->
	<!-- === Convert CameCaseText to camel-case-text                             === -->
	<!-- === (c) Inventic s.r.o. ORM Designer team (http://www.orm-designer.com) === -->
	<!-- =========================================================================== -->
	<xsl:template name="ConvertCamelToXmlStyle">
		<xsl:param name="text"/>
		<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="contains($Upper,node())">
					<xsl:if test="position()>1">
						<xsl:text>-</xsl:text>
					</xsl:if>
					<xsl:value-of select="translate(node(),$Upper,$Lower)"/>
				</xsl:when>
				<xsl:otherwise>
					<xsl:value-of select="node()"/>
				</xsl:otherwise>
			</xsl:choose>
		</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 *