VeeBot
VeeBot

Reputation: 13

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

I have a following in my XML file:

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

I am trying to produce a XSL that will remove the ref attribute in any element or just replace the ref attribute's value with something hardcoded like "XXX". I would prefer to find and remove the ref attribute as my first option.

Below is the XSL I am working with, but it doesn't actually remove the attributes in question:

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

Upvotes: 1

Views: 2883

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116982

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

The main problem with your approach is that your second template is never applied, because your first template does not apply any templates.

Try it this way:

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>

Upvotes: 2

Related Questions