使用 XSLT 将平面 XML 结构更改为分层结构 [英] change flat XML structure to hierarchical structure with XSLT

查看:33
本文介绍了使用 XSLT 将平面 XML 结构更改为分层结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如我需要转换

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

<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 元素进行分组:

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>

这篇关于使用 XSLT 将平面 XML 结构更改为分层结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆