xsl sum siblings based on node value

2019-06-24 13:53发布

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"

标签: xslt xslt-2.0
1条回答
迷人小祖宗
2楼-- · 2019-06-24 14:35

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)"/>
查看更多
登录 后发表回答