如何通过它的位置获得元素的总和。我有以下 XML 并且想使用 XSLT 按位置获取 DonneeRensCompl 的总和

How to get sum of elements by it's position. I have below XML and wanted to get sum of DonneeRensCompl by position using XSLT

我有下面的代码,想通过它的位置得到 DonneeRensCompl 的总和。示例 Position1 = 3.60 (1.30+ 2.30 = 3.60) 同样适用于所有可能的位置。

    <DATA_DS>
<R>
<Annee>2021</Annee>
<CaseRensCompl>
<CodeRensCompl>235</CodeRensCompl>
<DonneeRensCompl>1.30</DonneeRensCompl>
</CaseRensCompl>
<CaseRensCompl>
<CodeRensCompl>B-1</CodeRensCompl>
<DonneeRensCompl>10650.00</DonneeRensCompl>
</CaseRensCompl>
<CaseRensCompl>
<CodeRensCompl>RZ-RJ</CodeRensCompl>
<DonneeRensCompl>10650.00</DonneeRensCompl>
</CaseRensCompl>
</R>
<R>
<Annee>2021</Annee>
<CaseRensCompl>
<CodeRensCompl>235</CodeRensCompl>
<DonneeRensCompl>2.30</DonneeRensCompl>
</CaseRensCompl>
<CaseRensCompl>
<CodeRensCompl>RZ-CA</CodeRensCompl>
<DonneeRensCompl>10650.00</DonneeRensCompl>
</CaseRensCompl>
</R>

如果事先不知道位置的个数,那么必须循环递增位置,直到当前位置没有节点:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/DATA_DS">
    <root>
        <xsl:call-template name="sum-by-positions"/>
    </root>
</xsl:template>

<xsl:template name="sum-by-positions">
    <xsl:param name="i" select="1"/>
    <xsl:variable name="cases" select="//CaseRensCompl[$i]" />
    <xsl:if test="$cases">
        <sum position="{$i}">
            <xsl:value-of select="format-number(sum($cases/DonneeRensCompl), '#,##0.00')"/>
        </sum>
        <!-- recursive call -->
        <xsl:call-template name="sum-by-positions">
            <xsl:with-param name="i" select="$i + 1"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

应用于您的输入示例,这将产生:

结果

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <sum position="1">3.60</sum>
   <sum position="2">21,300.00</sum>
   <sum position="3">10,650.00</sum>
</root>

要了解其工作原理,请阅读 XPath 1.0 specification 中的这条注释:

NOTE: The location path //para[1] does not mean the same as the location path /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents.