XSLT,XPath,使用current的值进行选择和求和

问题描述

我有一个值列表,需要用来汇总不同的项目数量一个简单的版本如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<Items xmlns:boomi="http://boomi.com/custom-function">
    <Item>
        <id>801</id>
        <qty>0</qty>
    </Item>
    <Item>
        <id>802</id>
        <qty>1</qty>
    </Item>
    <Item>
        <id>802</id>
        <qty>1</qty>
    </Item>
</Items>

我正在使用以下XSLT

<Items>
    <xsl:for-each select="distinct-values(/Items/Item/id)" >
        <Item>
            <id>
                <xsl:value-of select="current()" />
            </id>
        </Item>
    </xsl:for-each>
</Items>

生成以下文档

<?xml version="1.0" encoding="UTF-8"?>
<Items xmlns:boomi="http://boomi.com/custom-function">
    <Item>
        <id>801</id>
    </Item>
    <Item>
        <id>802</id>
    </Item>
</Items>

但是我还需要包括数量。我已经尝试了一些方法,这是最接近的方法,但是不起作用:

<Items>
    <xsl:for-each select="distinct-values(/Items/Item/id)" >
        <Item>
            <id>
                <xsl:value-of select="current()" />
                <xsl:value-of select="sum(/Items/Item[id=current()]/qty)" />
            </id>
        </Item>
    </xsl:for-each>
</Items>

我认为它不起作用,因为current()是一个实际的节点?我正在努力做到这一点:

<?xml version="1.0" encoding="UTF-8"?>
<Items xmlns:boomi="http://boomi.com/custom-function">
    <Item>
        <id>801</id>
        <qty>0</qty>
    </Item>
    <Item>
        <id>802</id>
        <qty>2</qty>
    </Item>
</Items>

我是完全以错误的方式来做这件事吗?谢谢。

解决方法

这是使用michael.hor257k指示的使用XSLT 2.0的解决方案

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:boomi="http://boomi.com/custom-function">
    <xsl:template match="/">
<Items>
    <xsl:for-each-group select="/Items/Item" group-by="id" >
        <Item>
            <id>
                <xsl:value-of select="current-grouping-key()" />
            </id>
           <qty>
               <xsl:value-of select="sum(current-group()/qty)" />
          </qty>
        </Item>
    </xsl:for-each-group>
</Items>

    </xsl:template>
</xsl:stylesheet>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...