convert single digit to two digits

O

ofuuzo1

I have the following xml file and I want to concat the values and if
a value is less that two digits, it is converted to two digits

<date>
<day>1 </day>
<month>11</month>
<year>2008</year>
<date>
.....

The result will be 01112008

How can I do it using xslt?

Thanks
Ofuuzo
 
M

Martin Honnen

I have the following xml file and I want to concat the values and if
a value is less that two digits, it is converted to two digits

<date>
<day>1 </day>
^
There is a space there, does that belong there?
<month>11</month>
<year>2008</year>
<date>
....

The result will be 01112008

How can I do it using xslt?

Well with XSLT 2.0 you can write a function e.g.

<xsl:function name="my:pad" as="xs:string">
<xsl:param name="input" as="xs:string"/>
<xsl:variable name="n" as="xs:string"
select="normalize-space($input)"/>
<xsl:sequence
select="if (string-length($n) &lt; 2) then
concat('0', $n) else $n"/>
</xsl:function>

and use it like this:

<xsl:template match="date">
<xsl:value-of select="*/my:pad(.)" separator=""/>
</xsl:template>

XSLT 2.0 is supported by Saxon (<http://saxon.sourceforge.net/>),
Gestalt (<http://gestalt.sourceforge.net>) and AltovaXML
(<http://www.altova.com/altovaxml.html>)

Let us know whether that helps or whether you want an XSLT 1.0 solution.
 
M

Martin Honnen

I have the following xml file and I want to concat the values and if
a value is less that two digits, it is converted to two digits

<date>
<day>1 </day>
<month>11</month>
<year>2008</year>
<date>
....

The result will be 01112008

How can I do it using xslt?

Here is an XSLT 1.0 solution with a named template:

<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

<xsl:eek:utput method="text"/>

<xsl:template name="pad">
<xsl:param name="input"/>
<xsl:param name="length" select="2"/>
<xsl:variable name="n" select="normalize-space($input)"/>
<xsl:variable name="padchars" select="'00000000000000000000'"/>
<xsl:value-of select="concat(substring($padchars, 1, $length -
string-length($n)), $n)"/>
</xsl:template>

<xsl:template match="date">
<xsl:for-each select="*">
<xsl:call-template name="pad">
<xsl:with-param name="input" select="."/>
</xsl:call-template>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top