change flat XML structure to hierarchical structur

2019-05-31 01:59发布

I'm trying to use XSLT to create a hierarchical XML file from a flat XML file, and not sure what the best approach is.

e.g. I need to convert

<root>
<inventory bag="1" fruit="apple"/>
<inventory bag="1" fruit="banana"/>
<inventory bag="2" fruit="apple"/>
<inventory bag="2" fruit="orange"/>
</root>

to

<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>

for N bags/fruits

标签: xml xslt xpath
2条回答
淡お忘
2楼-- · 2019-05-31 02:25

Group inventory elements based on the value of their bag attribute:

<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>
查看更多
仙女界的扛把子
3楼-- · 2019-05-31 02:28

xsl:for-each your nodes twice, or use xsl:template with different modes.

查看更多
登录 后发表回答