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

时间:2017-06-07 19:26:35

标签: xml xslt stylesheet

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

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

Colo应为Color。现在在一些文件中已经手动更正了这两个属性:

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

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

<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>

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

1 个答案:

答案 0 :(得分:2)

我想你想做:

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元素;否则它会删除它。