另一个属性的属性值总和

问题描述 投票:0回答:1

我有以下 xml

<?xml version="1.0" encoding="UTF-8"?>
<Containers>
  <ContainerGroup Type="40HC" Quantity="1"/> 
  <ContainerGroup Type="40HC" Quantity="3"/> 
  <ContainerGroup Type="42PL" Quantity="4"/> 
  <ContainerGroup Type="40HC" Quantity="2"/> 
</Containers>

需要写一段xsl 1.0代码,这样结果就是

<Sum>40HC-6||42PL-4</Sum>

尝试使用下面的代码但没有成功

<xsl:for-each select="Containers/ContainerGroup/@Type">
<xsl:variable name="sumQuantity" select="sum(@Quantity)" />
<xsl:if test="position() != 1">||</xsl:if>
<xsl:value-of select="concat(@Type,'-',$sumQuantity)"/>
</xsl:for-each>

编辑1 使用 Muenchian 方法,在下面的代码中开发,但它不起作用

<xsl:key name="container-by-type" match="Containers/ContainerGroup" use="Containers/ContainerGroup/@Type"/>
<xsl:template name="sumQuantity">       
<xsl:for-each select="//Containers/ContainerGroup[generate-id() = generate-id(key('container-by-type', Containers/ContainerGroup/@Type)[1])]">
<xsl:variable name="grp" select="key('container-by-type', Containers/ContainerGroup/@Type)" />
<xsl:if test="position() != 1">||</xsl:if>
<xsl:value-of select="concat(Containers/ContainerGroup/@Type,'-',sum($grp/@Quantity))"/>
</xsl:for-each>
</xsl:template>
xslt-1.0
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:key name="container-by-type" match="ContainerGroup" use="@Type"/>

<xsl:template match="/Containers">
    <Sum>
        <!-- create a group for each distinct type -->
        <xsl:for-each select="ContainerGroup[generate-id()=generate-id(key('container-by-type', @Type)[1])]">
            <!-- output the type -->
            <xsl:value-of select="@Type" />
            <xsl:text>-</xsl:text>
            <!-- sum the curent group's quantities -->
            <xsl:value-of select="sum(key('container-by-type', @Type)/@Quantity)" />
            <xsl:if test="position()!=last()">||</xsl:if>
        </xsl:for-each>
    </Sum>
</xsl:template> 

</xsl:stylesheet>
© www.soinside.com 2019 - 2024. All rights reserved.