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"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <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="
   substring(
     string-join (
       ($stringToPad, for $i in (1 to $length) return $padChar)
       ,'')
    ,1,$length)
"/>
    </xsl:function>

</xsl:stylesheet>
 

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)" />
    </xsl:template>
 

The input XML like

 
<test>
  <short_value>123</short_value>
</test>

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

Advertisements

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.