使用XSLT将平面XML结构更改为分层结构

change flat XML structure to hierarchical structure with XSLT

我正在尝试使用XSLT从平面XML文件创建分层XML文件,但不确定最好的方法是什么。

例如我需要转换

1
2
3
4
5
6
<root>
<inventory bag="1" fruit="apple"/>
<inventory bag="1" fruit="banana"/>
<inventory bag="2" fruit="apple"/>
<inventory bag="2" fruit="orange"/>
</root>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<inventory>
<baglist>
<bag id="1"/>
<bag id="2"/>
</baglist>

<bag id="1">
<fruit id="apple"/>
<fruit id="banana"/>
</bag>

<bag id="2">
<fruit id="apple"/>
<fruit id="orange"/>
</bag>
</inventory>

用于N袋/水果


根据bag属性的值将inventory元素分组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="byBag" match="root/inventory" use="@bag" />
    <xsl:template match="/">
        <inventory>
            <baglist>
                <xsl:apply-templates mode="baglist" />
            </baglist>
            <xsl:apply-templates />
        </inventory>
    </xsl:template>
    <xsl:template
        match="root/inventory[generate-id() =
                             generate-id(key('byBag', @bag)[1])]"

                        mode="baglist">
        <bag id="{@bag}" />
    </xsl:template>

    <xsl:template
        match="root/inventory[generate-id() =
                            generate-id(key('byBag', @bag)[1])]"
>
        <bag id="{@bag}">
            <xsl:apply-templates select="key('byBag', @bag)"
                mode="details" />
        </bag>
    </xsl:template>

    <xsl:template match="inventory" mode="details">
        <fruit id="{@fruit}" />
    </xsl:template>
</xsl:stylesheet>


xsl:for-每个节点两次,或使用xsl:template的不同模式。