Software Development
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!
| Reference: | right-pad values with XSLT from our JCG partner Pascal Alma at the The Pragmatic Integrator blog. |



