Subject: Re: [xsl] sum for a specific attribute From: mpfingstler@xxxxxxxxxxxxxxxxxxxx Date: Wed, 17 Apr 2002 18:26:55 -0500 |
-- Hello friends, -- Is there a way to get the sum of elements with a condition on the attribure -- . -- In my case, I need to get the sum of the detail/@value where the -- detail/@type is 'A' -- and the sum of the detail/@value where the detail/@type is 'C' . -- -- <account> -- <detail type="A" value="123.56" /> -- <detail type="A" value="456.78" /> -- <detail type="A" value="12.3" /> -- <detail type="B" value="42.3" /> -- <detail type="B" value="96.2" /> -- <detail type="C" value="14.5" /> -- <detail type="C" value="22.3" /> -- <detail type="C" value="17.1" /> -- <detail type="C" value="98.6" /> -- </account> As has already been said, you can just say 'select="sum(detail[@type = 'A']/@value)"', and likewise for 'B' and 'C', which works well if you know in advance what the values for @type will be. If you don't know, or don't want to hard-code, the following will work: <xsl:key name="val" match="@value" use="../@type"/> <xsl:for-each select="detail[not(preceding::detail/@type = @type)]"> <xsl:value-of select="sum(key('val', @type))"/> </xsl:for-each> <xsl:for-each select="account/detail[not(preceding::detail/@type = @type)]"> selects each detail node where the type attribute of it is not equal to the type attribute in any node that came before it. If you were to look at values of the nodes that came back, they would be "123.56", "42.3", and "14.5". <xsl:value-of select="sum(key('val', @type))"/> uses the key we declared to give us value attributes where the type attribute matches the one we ask for, and sums the resulting node-set. Running the above on your XML produces the following: 592.6399999999999 138.5 152.5 Hope this helps (or makes any sense at all). Mark XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list
Current Thread |
---|
|
<- Previous | Index | Next -> |
---|---|---|
RE: [xsl] outputting the document e, Michael Kay | Thread | [xsl] Newbie questions on example f, Yosuke Ichikawa |
[xsl] outputting the document encod, Michael Clark | Date | RE: [xsl] <MsSinceMidnight1Jan1970>, Dan Diebolt |
Month |