如何使用 XSL/XSLT 删除属性或替换属性值?

How to remove attribute or replace attribute value using XSL/XSLT?

我的 XML 文件中有以下内容:

  <Hits>
    <Hit status="good">     
      <batter ref="4">Sample Text 1</batter>
      <contexts ref="5">Sample Text 2</contexts>
    </Hit>
    <Hit status="bad">
      <batter ref="7">Sample Text 3</batter>
      <contexts ref="" />
    </Hit>
  </Hits>

我正在尝试生成一个 XSL,它将删除任何元素中的 ref 属性,或者仅将 ref 属性的值替换为 "XXX" 等硬编码的内容。我更愿意找到并删除 ref 属性作为我的第一个选项。

下面是我正在使用的 XSL,但它实际上并没有删除有问题的属性:

<xsl:template match="Hit">
   <xsl:copy-of select="." />
   <xsl:text>
</xsl:text>
</xsl:template>



<xsl:template match="/Hit/batter/@ref">
        <xsl:attribute name="ref">
            <xsl:value-of select="$mycolor"/>
        </xsl:attribute>
</xsl:template>

I am trying to produce a xsl that will ... replace the attribute ref value with something hardcoded

你的方法的主要问题是你的第二个模板从未被应用,因为你的第一个模板没有应用任何模板。

这样试试:

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="@ref">
    <xsl:attribute name="ref">place a hard-coded value here</xsl:attribute>
</xsl:template>

</xsl:stylesheet>