user1555096
user1555096

Reputation: 43

xsl sum siblings based on node value

I need to apply an xsl transformation that sums certain node values based on the value of one of its sibling nodes. Here's my xml pseudo code:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<Message>
    <Body>
        <Order>
            <Item>
                <.../>
                <Type>widget</Type>
                <Qty>20</Qty>
                <.../>
            </Item>
            <Item>
                <.../>
                <Type>gadget</Type>
                <Qty>10</Qty>
                <.../>
            </Item>
            <Item>
                <.../>
                <Type>widget</Type>
                <Qty>5</Qty>
                <.../>
            </Item>
            <Item/>
        </Order>
    </Body>
</Message>

The desired result of the the quantity summation for all items of type 'widget' is 25

<xsl:value-of select="sum(/Message/Body/Order/Item/Qty)"/>

is yielding 35

My xsl stylesheet details

xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
version="2.0"

Upvotes: 4

Views: 469

Answers (1)

Fung
Fung

Reputation: 3558

Try to add predicates to find the nodes that you're interested (i.e. 'widget') only:

<xsl:value-of select="sum(/Message/Body/Order/Item[Type = 'widget']/Qty)"/>

Upvotes: 3

Related Questions