5.3 Number Functions

The XPath number functions all return numbers. However, none of the XSLT functions return numbers. The number functions are ceiling( ), floor( ), number( ), round( ), and sum( ). The node-set functions count( ), last( ), and position( ) also return numbers, as does the string function string-length( ).

5.3.1 The sum( ) Function

The sum( ) function takes a single node-set as an argument and returns or adds up a sum of numbers from that node-set. The document math.xml contains a group of operand elements, each with numeric content:

<math>  <operand>12</operand>  <operand>23</operand>  <operand>45</operand>  <operand>56</operand>  <operand>75</operand> </math>

You can use the sum( ) function in sum.xsl to add these numbers and return the sum:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/>     <xsl:template match="math">  <xsl:value-of select="sum(operand)"/> </xsl:template>     </xsl:stylesheet>

If applied to math.xml, this stylesheet will produce a sum of the numbers in all the operand children of math:

211

5.3.2 The round( ) Function

Taking a number as an argument, the round( ) function returns an integer that is rounded closest to the value of the function's argument. Consider round.xml:

<math>  <down>   <operand>12.12</operand>   <operand>23.22</operand>  </down>  <up>   <operand>12.15</operand>   <operand>23.73</operand>  </up> </math>

Then apply the stylesheet round.xsl:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/>     <xsl:template match="math">  <xsl:apply-templates select="up|down"/> </xsl:template>     <xsl:template match="up|down">  <xsl:value-of select="round(sum(operand))"/>  <xsl:text> </xsl:text> </xsl:template>     </xsl:stylesheet>

The sum( ) function returns a number to round( ). The stylesheet finds the up or down children of operand. When it finds them, it outputs the rounded sum of the operands:

35 36

The content of the operand children of down, 12.12, and 23.22 is converted to numbers, summed, and then rounded down to 35. On the other hand, the content of the operand children of up, 12.15, and 23.73 is converted to numbers, summed, and then rounded up to 36.

I'll wrap up with string functions.



Learning XSLT
Learning XSLT
ISBN: 0596003277
EAN: 2147483647
Year: 2003
Pages: 164

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net