将部分内容移至其他重复部分

时间:2019-06-23 13:37:17

标签: xml xslt

我有一个XML,该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中。 我该怎么做?

1 个答案:

答案 0 :(得分:0)

您无法在模板中定义模板。请改用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/*" />