XSLT:如果不存在则重命名属性

XSLT: Rename attribute if not exists

我有很多 XML 个包含拼写错误的属性的文件:

<Part id="1">
  <Attribute Name="Colo" Value="Red" />
</Part>

Colo 应该是 Color。现在在一些文件中,这已被手动更正,然后两个属性都存在:

<Attribute Name="Colo" Value="Red" />
<Attribute Name="Color" Value="Blue" />

我有一个将 Colo 属性重命名为 Color 的 XSL 转换,但是当更正的属性已经存在时,我不知道如何避免这种情况。

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

<xsl:template match="Attribute/@Name[. = 'Colo']">
    <xsl:attribute name="Name">
        <xsl:value-of select="'Color'"/>
    </xsl:attribute>
</xsl:template>

如果已经有正确的属性,如何不重命名?

我想你想做的是:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="Attribute[@Name = 'Colo']">
    <xsl:if test="not(../Attribute[@Name = 'Color'])">
        <Attribute Name="Color" Value="{@Value}" />
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

如果 Attribute 没有名称正确的同级元素,这将修改名称拼写错误的元素;否则它只会删除它。