gpt4 book ai didi

xslt - 不使用sum函数计算数组元素的总和

转载 作者:行者123 更新时间:2023-12-05 00:35:20 25 4
gpt4 key购买 nike

我是 xslt 的新手。我有一个像

<EmpCollection>
<Emp>
<Name>Sai</Name>
<Sal>7000</Sal>
</Emp>
<Emp>
<Name>Nari</Name>
<Sal>7400</Sal>
</Emp>
<Emp>
<Name>Hari</Name>
<Sal>9000</Sal>
</Emp>
<Emp>
<Name>Suri</Name>
<Sal>8900</Sal>
</Emp>
</EmpCollection>

现在我想在不使用 sum() 函数的情况下添加工资总额。
我想以一种清晰的方式学习 xslt :-)

最佳答案

I. 可能是最简单的解决方案之一 :

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="Sal">
<xsl:param name="pSum" select="0"/>
<xsl:apply-templates select="following::Sal[1]">
<xsl:with-param name="pSum" select="$pSum + ."/>
</xsl:apply-templates>
</xsl:template>

<xsl:template match="Sal[not(following::Sal)]">
<xsl:param name="pSum" select="0"/>
<xsl:value-of select="$pSum + ."/>
</xsl:template>

<xsl:template match="/">
<xsl:apply-templates select="descendant::Sal[1]"/>
</xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时 :
<EmpCollection>
<Emp>
<Name>Sai</Name>
<Sal>7000</Sal>
</Emp>
<Emp>
<Name>Nari</Name>
<Sal>7400</Sal>
</Emp>
<Emp>
<Name>Hari</Name>
<Sal>9000</Sal>
</Emp>
<Emp>
<Name>Suri</Name>
<Sal>8900</Sal>
</Emp>
</EmpCollection>

产生了想要的正确结果:
32300

二、更通用的解决方案是使用 FXSL 2.x f:foldl() 功能如下:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/" exclude-result-prefixes="f">
<xsl:import href="../f/func-foldl.xsl"/>
<xsl:import href="../f/func-Operators.xsl"/>

<xsl:output encoding="UTF-8" omit-xml-declaration="yes"/>

<xsl:template match="/">
<xsl:value-of select="f:foldl(f:add(), 0, /*/*/Sal)"/>
</xsl:template>
</xsl:stylesheet>

当此 XSLT 2.0 转换应用于同一个 XML 文档(上图)时,会产生相同的正确和想要的结果 :
32300

您可以将任何双参数函数作为参数传递给 f:foldl()并产生不同问题的解决方案 .

例如,通过 f:mult()而不是 f:add() (并将“零”参数更改为 1 )产生工资的乘积:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/" exclude-result-prefixes="f">
<xsl:import href="../f/func-foldl.xsl"/>
<xsl:import href="../f/func-Operators.xsl"/>

<xsl:output encoding="UTF-8" omit-xml-declaration="yes"/>

<xsl:template match="/">
<xsl:value-of select="f:foldl(f:mult(), 1, /*/*/Sal)"/>
</xsl:template>
</xsl:stylesheet>

将此转换应用于同一个 XML 文档的结果现在是所有 Sal 的结果。元素 :
4.14918E15

三、在 XSLT 3.0 (XPath 3.0) 中可以使用标准 fold-left() fold-right() 功能与之前的解决方案完全相同 .

关于xslt - 不使用sum函数计算数组元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12834461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com