首页 > 解决方案 > 将部分内容移动到其他重复部分

问题描述

我有一个 XML,它使用我用于文档生成的新格式。出于兼容性原因,我想在生成旧文档时保留不同的格式。因此,我想将 ADDRESSES 块内的所有内容移动到每个 ORDERS/ORDER 块。

简化的示例 XML:

<?xml version="1.0" encoding="ISO8859-1"?>
<XML>
    <ADDRESSES>
        <ADDRESSEE>
            ...
        </ADDRESSEE>
        <ORDCMP>
            ...
        </ORDCMP>
        <ORDCUSTOMER>
            ...
        </ORDCUSTOMER>
    </ADDRESSES>
    <ORDERS>
        <ORDER>

        </ORDER>
        <ORDER>
        </ORDER>
        <ORDER>
        </ORDER>
    </ORDERS>
</XML>

我尝试使用 XSLT 删除有效的 ADDRESSES 块,然后将 ADDRESSES 块中的每个元素复制到每个不起作用的 ORDERS/ORDER 块中。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output indent="yes"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- Remove the whole ADDRESSES block -->
    <xsl:template match="ADDRESSES">
    </xsl:template>

    <!-- And now start adding individual ADDRESSES items to each order -->
    <xsl:template match="ORDERS/ORDER">
        <xsl:apply-templates select="@*|node()"/>
        <xsl:copy>
            <xsl:template match="ADDRESSES/ADDRESSEE">
                <xsl:copy>
                    <xsl:apply-templates/>
                </xsl:copy>
            </xsl:template>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

我希望我的 XML 是:

<?xml version="1.0" encoding="ISO8859-1"?>
<XML>
    <ORDERS>
        <ORDER>
            <ADDRESSEE>
                ...
            </ADDRESSEE>
            <ORDCMP>
                ...
            </ORDCMP>
            <ORDCUSTOMER>
                ...
            </ORDCUSTOMER>
        </ORDER>
        <ORDER>
            <ADDRESSEE>
                ...
            </ADDRESSEE>
            <ORDCMP>
                ...
            </ORDCMP>
            <ORDCUSTOMER>
                ...
            </ORDCUSTOMER>
        </ORDER>
        <ORDER>
            <ADDRESSEE>
                ...
            </ADDRESSEE>
            <ORDCMP>
                ...
            </ORDCMP>
            <ORDCUSTOMER>
                ...
            </ORDCUSTOMER>
        </ORDER>
    </ORDERS>
</XML>

当然,除了 ADDRESSES 块之外,我想保留 XML 中已经存在的所有内容。我怎样才能做到这一点?

标签: xmlxslt

解决方案


您不能在模板中定义模板。改为使用xsl:copy-of。因此,将您的第三个模板更改为

<xsl:template match="ORDERS/ORDER">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <xsl:copy-of select="/XML/ADDRESSES/*" />
    </xsl:copy>
</xsl:template>

这会将所有元素复制ADDRESSES到每个ORDER元素。

或者,如果不同的订单组有多个ADDRESSES,您可以尝试使用相对路径

<xsl:copy-of select="../../ADDRESSES/*" />

推荐阅读