Padding number with leading zeros in XSLT 1.0

对着背影说爱祢 提交于 2019-12-01 04:11:36

I need to pad this with leading zeros to a length of 15 in the output (

That would be

substring(
  concat('000000000000000', msg:BankAccount/msg:Counter), 
  string-length(msg:BankAccount/msg:Counter) + 1, 
  15
)

Another approach is

substring(string(1000000000000000 + $x), 2)

It can be also done using string-format

<xsl:value-of select="format-number(msg:BankAccount/msg:Counter, '000000000000000')" />

in general:

<xsl:value-of select="format-number(number_you_would_like_to_padd, 'string_how_much_zeros_you_would like')" />

Another option is xsl:number...

<xsl:number value="number_to_format" format="000000000000001"/>

Full Example...

XML Input

<doc>
    <test>1</test>
    <test>11</test>
    <test>250</test>
</doc>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="test">
    <xsl:number value="." format="000000000000001"/>
    <xsl:text>&#xA;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

Output

000000000000001
000000000000011
000000000000250

Fiddle: http://xsltfiddle.liberty-development.net/pPzifpg

Another option to consider....

<xsl:apply-templates select="Groups/Group[@Name='TheSource']/Field[@Name='BankAccount']" />
<xsl:text>999999999999999</xsl:text>
<!-- uncomment below and comment above line to use without test number -->
<!-- <xsl:text>|</xsl:text> -->

<xsl:template match="Groups/Group[@Name='BankAcctFile']/Field[@Name='BankAccount']">
    <xsl:call-template name="padleft">
        <xsl:with-param name="padChar" select="'0'" />
        <xsl:with-param name="padVar" select="substring(current(),1,15)" />
        <xsl:with-param name="length" select="15" />
    </xsl:call-template>
</xsl:template>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!