XSLT - 通过比较其他元素属性来复制属性

XSLT - copy attribute by comparing other element attribute

我有一个这样的样本xml,

<doc>
    <aa type="aaa" id="ggg">text</aa>
    <aa type="bbb" id="hhh">text</aa>
    <aa type="ccc" id="iii">text</aa>
    <aa type="ccc" id="jjj">text</aa>
    <aa type="bbb" id="kkk">text</aa>
    <aa type="aaa" id="lll">text</aa>
</doc>

如您所见,此处存在 2 个具有相等 type 属性的元素,我需要的是如果类型属性相等的元素交换 id 属性值。

所以,对于上面的例子,输出应该是,

<doc>
    <aa type="aaa" id="lll">text</aa>
    <aa type="bbb" id="kkk">text</aa>
    <aa type="ccc" id="jjj">text</aa>
    <aa type="ccc" id="iii">text</aa>
    <aa type="bbb" id="hhh">text</aa>
    <aa type="aaa" id="ggg">text</aa>
</doc>

我已经编写了以下 xsl 来执行此操作,

<xsl:template match="aa[@type='aaa' or @type='bbb' or @type='ccc'][1]">
        <xsl:copy>
            <xsl:if test="following::aa[@type=self::node()/@type]">
                <xsl:attribute name="id">
                    <xsl:value-of select="following::aa[@type=self::node()/@type]/@type"/>
                </xsl:attribute>
            </xsl:if>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="aa[@type='aaa' or @type='bbb' or @type='ccc'][2]">
        <xsl:copy>
            <xsl:if test="following::aa[@type=self::node()/@type]">
                <xsl:attribute name="id">
                    <xsl:value-of select="preceding::aa[@type=self::node()/@type]/@type"/>
                </xsl:attribute>
            </xsl:if>
        </xsl:copy>
    </xsl:template>

但这并不像预期的那样,有人建议我如何使用 XSLT 执行此操作吗?

试试这个

<xsl:stylesheet
    version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes" omit-xml-declaration="yes"/>

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

    <xsl:template match="aa">
        <xsl:variable name="type" select="@type"/>
        <xsl:copy>
            <xsl:apply-templates select="@type"/>
            <xsl:choose>
                <xsl:when test="following::aa[@type=$type]">
                    <xsl:attribute name="id">
                        <xsl:value-of select="following::aa[@type=$type]/@id"/>
                    </xsl:attribute>
                </xsl:when>
                <xsl:when test="preceding::aa[@type=$type]">
                    <xsl:attribute name="id">
                        <xsl:value-of select="preceding::aa[@type=$type]/@id"/>
                    </xsl:attribute>
                </xsl:when>
            </xsl:choose>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>