如何使用XSLT基于2个元素进行求和

时间:2017-01-23 07:48:52

标签: xml xslt

我想对每个时间戳和人口的人口数进行求和。 Reasoncode。鉴于下面的示例代码,它不起作用。你能不能帮助我让它工作

我的XML:

我使用以下XML作为输入文件

<?xml version="1.0" encoding="UTF-8"?>
<Earnings>
    <Collection>
        <Timestamp>20170101</Timestamp>
        <Points>100</Points>
        <ReasonCode>AN</ReasonCode>
    </Collection>
    <Collection>
        <Timestamp>20170102</Timestamp>
        <Points>100</Points>
        <ReasonCode>AN</ReasonCode>
    </Collection>
    <Collection>
        <Timestamp>20170101</Timestamp>
        <Points>10000</Points>
        <ReasonCode>BP</ReasonCode>
    </Collection>
    <Collection>
        <Timestamp>20170101</Timestamp>
        <Points>10000</Points>
        <ReasonCode>BP</ReasonCode>
    </Collection>
    <Collection>
        <Timestamp>20170102</Timestamp>
        <Points>100</Points>
        <ReasonCode>PPTS</ReasonCode>
    </Collection>
</Earnings>

我的XSLT

我使用了以下用于将XML转换为指定格式的XSLT

<?xml version="1.0" encoding="UTF-16"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:key name="Earnings" match="Earnings/Collection" use="concat(Timestamp, '+',ReasonCode)"/>
    <xsl:template match="Earnings">
        <Earnings>
            <xsl:for-each select="Collection[generate-id() = generate-id(key('Earnings', concat(Timestamp, '+',ReasonCode))[1])]">
                <xsl:sort select="concat(Timestamp, '+',ReasonCode)"/>
                <xsl:variable name="current-group" select="/Earnings/Collection[ReasonCode = current()/ReasonCode]"/>
                <Collection>
                    <Timestamp>
                        <xsl:value-of select="Timestamp"/>
                    </Timestamp>
                    <Points>
                        <xsl:value-of select="sum($current-group/Points)"/>
                    </Points>
                    <ReasonCode>
                        <xsl:value-of select="ReasonCode"/>
                    </ReasonCode>
                </Collection>
            </xsl:for-each>
        </Earnings>
    </xsl:template>
</xsl:stylesheet>

预期产出

<Collection>
    <Timestamp>20170101</Timestamp>
    <Points>100</Points>
    <ReasonCode>AN</ReasonCode>
</Collection>
<Collection>
    <Timestamp>20170101</Timestamp>
    <Points>2000</Points>
    <ReasonCode>BP</ReasonCode>
</Collection>
<Collection>
    <Timestamp>20170102</Timestamp>
    <Points>100</Points>
    <ReasonCode>AN</ReasonCode>
</Collection>
<Collection>
    <Timestamp>20170102</Timestamp>
    <Points>100</Points>
    <ReasonCode>PPTS</ReasonCode>
</Collection>

谢谢,
莫汉

1 个答案:

答案 0 :(得分:0)

变化:

<xsl:variable name="current-group" select="/Earnings/Collection[ReasonCode = current()/ReasonCode]"/>

为:

<xsl:variable name="current-group" select="key('Earnings', concat(Timestamp, '+',ReasonCode))"/>

您现在拥有的所有Collection与当前ReasonCode的{​​{1}}相同,无论其Collection如何。