You are not logged in.
Pages: 1
Padding Zeros to a Field with XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="//*[local-name()='CustomerCode']">
<!-- Define a variable to contain the length of the input value
The dot you see in the expression is the current element we are working on.
In this case CustomerCode is the Input Value. See the match above-->
<xsl:variable name="inputLength" select="string-length(.)" />
<xsl:copy>
<!-- Now we create a variable to hold our padding.
It is a substring of our 10 zeros less the length of our input -->
<xsl:variable name="padding" select="substring('0000000000',1,10 - $inputLength)"/>
<!-- Finally we simply concatinate our padding which is the correct length with the input value.
Don't forget the dot you see there is the current element we matched on in this case CustomerCode Input Value -->
<xsl:value-of select="concat($padding,.)" />
</xsl:copy>
</xsl:template>
<xsl:template match="//*[local-name()='SiteCode']">
<!-- Define a variable to contain the length of the input value
The dot you see in the expression is the current element we are working on.
In this case SiteCode is the Input Value. See the match above-->
<xsl:variable name="inputLength" select="string-length(.)" />
<xsl:copy>
<!-- Now we create a variable to hold our padding.
It is a substring of our 10 zeros less the length of our input -->
<xsl:variable name="padding" select="substring('0000000000',1,10 - $inputLength)"/>
<!-- Finally we simply concatinate our padding which is the correct length with the input value.
Don't forget the dot you see there is the current element we matched on in this case SiteCode Input Value -->
<xsl:value-of select="concat($padding,.)" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Here is the input XML you can test with
<?xml version="1.0" encoding="UTF-8"?>
<XServiceBroker xmlns="http://www.sxi.co.za/XMLSchema">
<CustomerCode>1222B3</CustomerCode>
<SiteCode>ZB22B3</SiteCode>
</XServiceBroker>
Credit goes to Kevin.
Offline
Is there a reason this is not being done with a standard XLayer rule?
Given a field called "aNum" that contains "12345" The following XLayer rule will product "0000012345"
<sxi:Rules>
<sxi:SubStringReplace>
<sxi:StartAt>-1</sxi:StartAt>
<sxi:Pattern>0000000000</sxi:Pattern>
<sxi:ReplaceWith input="yes">aNum</sxi:ReplaceWith>
</sxi:SubStringReplace>
</sxi:Rules>
No need to stylesheet Kung-Fu. Unless obviously you absolutely have to do it in a stylesheet.
Offline
Thx Sean, works like a charm.
Offline
Pages: 1