antonpug
antonpug

Reputation: 14286

XSLT Template to identify odd/even numbers?

I need to write an XSLT template to identify a string of numbers. How can i do that?

Upvotes: 1

Views: 3010

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243479

XSLT 1.0 solution:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>
 <xsl:param name="pNumbers" select="'2,23,12,251'"/>

 <xsl:template match="/">
     <xsl:call-template name="classify"/>
 </xsl:template>

 <xsl:template name="classify">
  <xsl:param name="pNums" select="$pNumbers"/>

  <xsl:if test="string-length($pNums)">
   <xsl:variable name="vN" select=
    "substring-before(concat($pNums, ','), ',')"/>
   <num odd="{$vN mod 2 = 1}">
    <xsl:value-of select="$vN"/>
   </num>

   <xsl:call-template name="classify">
    <xsl:with-param name="pNums" select=
     "substring-after($pNums, ',')"/>
   </xsl:call-template>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the wanted, correct classification is produced:

<num odd="false">2</num>
<num odd="true">23</num>
<num odd="false">12</num>
<num odd="true">251</num>

Upvotes: 1

Michael Kay
Michael Kay

Reputation: 163352

To split the string into a sequence of numbers, use tokenize() in XSLT 2.0, or the EXSLT str:tokenize in XSLT 1.0. To test whether a number $N is even, use $N mod 2 = 0

Upvotes: 2

Related Questions