Padding number with leading zeros in XSLT 1.0

We have a number in XML that can be up to 3 digits in a large XML file that needs to be converted to fixed-length text for upload to another system.

I need to overlay this with leading zeros to a length of 15 in the output (this is a fixed length text)

Examples:

 - 1 becomes   000000000000001
 - 11 becomes  000000000000011
 - 250 becomes 000000000000250

      

I've tried this:

<xsl:value-of select="substring(concat('000000000000000', msg:BankAccount/msg:Counter), 12, 15)"/>

      

to get 15 zeros at the beginning and take the substring, but I must have made a mistake with the substring, because in the results I get

0000000000000000000000009LLOYDS BANK PLC
00000000000000000000000010LLOYDS BANK PLC

      

I also tried format-number

but I am returning NaN

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

      

returns "NaN"

so what did I do wrong and what is the best way to do it?

+7


source to share


5 answers


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

It will be



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

      

+12


source


Another approach is



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

      

+10


source


This can be done using string format too

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

      

generally:

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

      

+8


source


Another option is xsl:number

...

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

      

Complete 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

+1


source


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>

      

0


source







All Articles