Description
The functx:avg-empty-is-zero function returns the average of the non-empty values in $values , over the number of nodes provided in $allNodes . This is useful for performing calculations where you want "missing" elements and/or attribute values to count as zero rather than not being included in the average at all.
Arguments and Return TypeName | Type | Description |
$values |
xs:anyAtomicType* |
the values to be averaged |
$allNodes |
node()* |
the sequence of all nodes to find the average over |
return value |
xs:double |
XSLT Function DeclarationSee XQuery definition. | <xsl:function name="functx:avg-empty-is-zero" as="xs:double"
xmlns:functx="http://www.functx.com">
<xsl:param name="values" as="xs:anyAtomicType*"/>
<xsl:param name="allNodes" as="node()*"/>
<xsl:sequence select="
if (empty($allNodes))
then 0
else sum($values[string(.) != '']) div count($allNodes)
"/>
</xsl:function>
|
Examples<xsl:variable name="in-xml" as="item()*"> | | <prices>
<price value="29.99" discount="10.00"/>
<price value="39.99" discount="6.00"/>
<price value="69.99"/>
<price value="49.99" discount=""/>
</prices> |
| </xsl:variable> |
XPath Example | Results | Explanation |
---|
functx:avg-empty-is-zero(
$in-xml//price/@discount, $in-xml//price) |
4 |
The average discount for the prices is 4, if you want the discount on the 3rd and 4th prices to be counted as zero. Using fn:avg($in-xml//price/@discount) function would have raised an error because the discount on the 4th price is not a valid number. If the 4th price did not have a discount attribute, it would return 8. |
See Alsofn:avg | The average of a sequence of values |
History |
Recommended Reading:
|