【问题标题】:XSLT: Rename attribute if not existsXSLT:如果不存在,则重命名属性
【发布时间】:2017-11-09 07:32:37
【问题描述】:

我有很多包含拼写错误的属性的 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>

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

【问题讨论】:

  • 如果存在更正的版本,您难道不应该删除带有Colo 名称的整个Attribute 元素吗?
  • 那是最好的,这就是我接下来要做的:)
  • 混淆您的“属性”实际上是元素,而它们的“名称”实际上是它们的“名称”属性的值......

标签: xml xslt stylesheet


【解决方案1】:

我想你想做:

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 元素没有名称正确的兄弟,这将修改名称拼写错误的Attribute 元素;否则它只会删除它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 2019-07-28
    • 2011-12-08
    • 2023-01-27
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多