Padding number with leading zeros in XSLT 1.0

扶醉桌前 提交于 2019-12-19 06:39:09

问题


We have a number in XML that can go up to 3 digits in a large XML file that has to be converted to fixed length text for loading into another system.

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

Examples:

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

I tried this:

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

to get the 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 it returns NaN

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

returns 'NaN'

so what have I done wrong and what is the best way to do this?


回答1:


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
)



回答2:


Another approach is

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



回答3:


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')" />



回答4:


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




回答5:


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>


来源:https://stackoverflow.com/questions/25662151/padding-number-with-leading-zeros-in-xslt-1-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!