home contribute faq download

FunctX XSLT Functions

functx:avg-empty-is-zero

The average, counting "empty" values as zero

Google
Webxsltfunctions.com

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 Type

NameTypeDescription
$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 Declaration

See 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 ExampleResultsExplanation
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 Also

fn:avgThe average of a sequence of values

History

Published OnLast UpdatedContributor(s)
2006-06-272007-02-26Priscilla Walmsley, Datypic, pwalmsley@datypic.com, http://www.datypic.com
Datypic XSLT Services

Recommended Reading:

XQuery