子节点上的XSLT组

时间:2018-04-29 01:51:47

标签: group-by xslt-1.0

我尝试在子节点组上转换XML。主要信息在 bill 节点中,必须按账单编号分组。

原始XML,这是原始XML的简化版

<items>
    <item>  
        <bill>10</bill>  
        <name>first (10)</name>
        <price>111</price>
    </item>
    <item>
        <bill>10</bill>
        <name>second (10)</name>
        <price>222</price>
    </item>
    <item>
        <bill>10</bill>
        <name>third (10)</name>
        <price>333</price>
    </item>
    <item>
        <bill>11</bill>
        <name>first (11)</name>
        <price>1</price>
    </item>
    <item>
        <bill>11</bill>
        <name>second (11)</name>
        <price>2</price>
    </item>
</items>

最终文件

<bills>
    <bill>
        <number>10</number>
        <items>
            <item>
                <nameitem>first (10)</nameitem>
                <priceitem>111</priceitem>
            </item>
            <item>
                <nameitem>second (10)</nameitem>
                <priceitem>222</priceitem>
            </item>
            <item>
                <nameitem>third (10)</nameitem>
                <priceitem>333</priceitem>
            </item>
        </items>
    </bill>
    <bill>
        <number>11</number>
        <items>
            <item>
                <nameitem>first (11)</nameitem>
                <priceitem>1</priceitem>
            </item>
            <item>
                <nameitem>second (11)</nameitem>
                <priceitem>2</priceitem>
            </item>
        </items>
    </bill>
</bills>

有工作的XSLT,用于基本分组,但我不知道如何在 bill 节点内构建另一个结构,基于最终的XML

    
<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:strip-space elements="*"/>
<xsl:key name="group-by-bill" match="item" use="bill"/>

<xsl:template match="items">
    <bills>
        <xsl:for-each select="item[generate-id()=generate-id (key('group-by-bill', bill)[1])]">
            <bill number="{bill}">
                <xsl:copy-of select="key('group-by-bill', bill)"/>
            </bill>
        </xsl:for-each>
    </bills>
</xsl:template>

1 个答案:

答案 0 :(得分:0)

使用此:

<xsl:template match="items">
    <bills>
        <xsl:for-each select="item[generate-id()=generate-id (key('group-by-bill', bill)[1])]">
            <bill>
                <number><xsl:value-of select="bill"/></number>
                <items>
                    <xsl:for-each select="//item[bill = current()/bill]">
                        <item>
                            <xsl:copy-of select="name|price"/>
                        </item>
                    </xsl:for-each>
                </items>
            </bill>
        </xsl:for-each>
    </bills>
</xsl:template>

请参阅https://xsltfiddle.liberty-development.net/jyH9rM5转换