Totaling Values
You can use the XPath sum() function to add up all the values of the nodes in a node set (Figure 4.20). It’s great for displaying data in tables and columns (Figure 4.21).
Figure 4.20 The XSLT in Figure 4.18 capitalized each wonder’s name as a header in the History section.
x s l t ... <tr> <td valign="top" align="right" colspan="4">Average Height: </td> <td valign="top"> <xsl:value-of select=" format-number( sum(/ancient_wonders/wonder/height) div count(/ancient_wonders/wonder/ height[.!=0]), '##0.0')" /> ft</td> </tr> ...
Figure 4.21. I’m creating a row to show the average height of all the wonders. To find the average, I use the sum() function to add up all the values of the height nodes. Then I divide the total height by the number of wonders which don’t have a height of zero. Finally, I format the output to show one value to the right of the decimal point.
Figure 4.22 The average height of all the wonders was nearly 20 stories high.
To total values:
- Type sum(.
- Then, type the path to the node set whose nodes should be totaled.
- Finally, type ) to complete the function.