I need some help with avg... I am attached files for xml --- I am struggling.... the question i have is :

1. What is the average speed of all the dinosaurs?
A. <xsl:value-of select="format-number((sum(dinosaurs/*/speed[@units='mph'])div count(dinosaurs/*/speed[@units='mph']))"/>ft
it does not work...

or
B. <xsl:value-of select="sum(//speed) div count(//speed)" />

or

C.9. <xsl:value-of select="format-number((sum(dinosaurs/*/speed[@units='mph'])div count(dinosaurs/*/speed[@units='mph']))"/>ft

Recommended Answers

All 2 Replies

speed in the second node is
no information about the speed
sum produces NaN ( not a number)
Helmut Hagemann

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
	<xsl:output method="xml" indent="yes"/>
	<xsl:template match="/">
		<Mittel>

			<xsl:call-template name="avg">
				<xsl:with-param name="kn" select="//speed"/>
				<xsl:with-param name="ho" select="count(//speed)"/>
			</xsl:call-template>
		</Mittel>
	</xsl:template>
	<xsl:template name="avg">
		<xsl:param name="kn"/>
		<xsl:param name="ho"/>
		<xsl:param name="ak" select="1"/>
		<xsl:param name="sum" select="0"/>
		<xsl:variable name="c" select="count($kn)"/>
		<xsl:choose>
			<xsl:when test="($ak &lt;= $c)and ($kn[$ak]!='0')">
				<xsl:call-template name="avg">
					<xsl:with-param name="ak" select="$ak+1"/>
					<xsl:with-param name="kn" select="$kn"/>
					<xsl:with-param name="sum" select="$sum + $kn[$ak]"/>
					<xsl:with-param name="ho" select="$ho"/>
				</xsl:call-template>
			</xsl:when>
			<xsl:when test="($ak &lt;= $c)and ($kn[$ak]='0')">

				<xsl:call-template name="avg">
					<xsl:with-param name="ak" select="$ak+1"/>
					<xsl:with-param name="kn" select="$kn"/>
					<xsl:with-param name="sum" select="$sum + $kn[$ak]"/>

					<xsl:with-param name="ho" select="$ho - 1"/>
				</xsl:call-template>
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="concat('entry ',$c,' ','used ',$ho,' avg ',$sum div $ho)"/>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>
</xsl:stylesheet>

Result

<?xml version='1.0' ?>
<Mittel>entry 3 used 2 avg 35</Mittel>

Helmut Hagemann

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.