right-pad values with XSLT

In this post an XSLT function that can be used to right-pad the value of an element with a chosen character to a certain length. No rocket science but this might become handy again so by putting it down here I don’t have to reinvent it later. The function itself looks like:

<xsl:stylesheet version="2.0"  xmlns:functx="http://my/functions"

    <xsl:function name="functx:pad-string-to-length" as="xsd:string">
    <xsl:param name="stringToPad" as="xsd:string?"/>
    <xsl:param name="padChar" as="xsd:string"/>
    <xsl:param name="length" as="xsd:integer"/>
    <xsl:sequence select="
     string-join (
       ($stringToPad, for $i in (1 to $length) return $padChar)


And with this function available you can use it like:

    <xsl:template match="/">
        <xsl:value-of select="functx:pad-string-to-length(//short_value, '0', 12)" />

The input XML like


will give as a result in this case:
By the way, this function only works with XSLT2!

About Pascal Alma

Pascal is a senior software developer and architect. Pascal has been designing and building applications since 2001. He is particularly interested in Open Source toolstack (Mule, Spring Framework, JBoss) and technologies like Web Services, SOA and Cloud technologies. Lately he is having great fun by building iOS apps with Swift. Specialties: JEE AWS XML/XSD/XSLT Web Services/SOA Mule ESB/ WSO2 ESB Maven Cloud Technology Swift/ iOS
This entry was posted in XML/ XSD/ XSLT and tagged . Bookmark the permalink.