change flat XML structure to hierarchical structure with XSLT
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
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>
xsl:for-each your nodes twice, or use xsl:template with different modes.
精彩评论