xsl-list
[Top] [All Lists]

[xsl] Using an empty xsl:for-each statement to "touch" elements

2013-12-12 04:40:55
Hi Folks,

Suppose you want to add together all the costs in this purchase order:

<purchase-order>
    <item>
        <cost>10</cost>
    </item>
    <item>
        <cost>20</cost>
    </item>
    <item>
        <cost>19</cost>
    </item>
    <item>
        <cost>25</cost>
    </item>
    <item>
        <cost>17</cost>
    </item>
</purchase-order>

The new XSLT 3.0 accumulator can be used. The accumulator is updated each time 
a <cost> element is "touched". To "touch" each <cost> element I have this empty 
loop:

<xsl:for-each select="item">
    <xsl:for-each select="cost"/>
</xsl:for-each>

That inner loop doesn't need any statements because its sole purpose is merely 
to "touch" the cost element, and thereby trigger the accumulator to be updated.

Here is the XSLT program with the accumulator:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
                         xmlns:xs="http://www.w3.org/2001/XMLSchema";
                         exclude-result-prefixes="#all"
                         version="3.0">
    
    <xsl:output method="xml" />
    
    <xsl:accumulator name="f:item-cost" 
                post-descent="f:total-item-cost" 
                as="xs:integer" 
                initial-value="0">
        <xsl:accumulator-rule match="cost" new-value="$value + xs:integer(.)"/>
    </xsl:accumulator>
    
    <xsl:template match="purchase-order">
        <Total-Cost>
            <xsl:for-each select="item">
                <xsl:for-each select="cost"/>
            </xsl:for-each>
            <xsl:value-of select="f:total-item-cost()" />
        </Total-Cost>
    </xsl:template>
    
</xsl:stylesheet>

I realize that this problem could be solved in other ways, but I wanted to show 
how it could be solved using an accumulator. And that invariably led me to an 
empty xsl:for-each statement.

Is there a better way to "touch" an element than using an empty xsl:for-each 
statement?

/Roger

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--


<Prev in Thread] Current Thread [Next in Thread>