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 IT consultant and has been working in IT since 1997. He is monitoring the latest development in new technologies (Mobile, Cloud, Big Data) closely and particularly interested in Java open source tool stacks, cloud related technologies like AWS and mobile development like building iOS apps with Swift. Specialties: Java/JEE/Spring Amazon AWS API/REST Big Data Continuous Delivery Swift/iOS
This entry was posted in XML/ XSD/ XSLT and tagged . Bookmark the permalink.