HelpMeWithXSLT
HelpMeWithXSLT

Reputation: 79

XSLT - Remove all Attributes Except for Specified Attributes

I am trying to find a way to remove all attributes in an XML document aside from a few specified ones. I am able to remove one attribute from a specified element, but I am unable to remove all attributes (minus the ones I want to keep) from all elements in the document.

For example: if i want to keep only id and class attributes,

this input:

<body>
<div id="div1" class="hello" length="1">inner text</div>
<span id="div2" class="bye" length="2">inner text</span>
<ol id="div3" class="goodbye" length="3">inner text</ol>
</body>

should be this output:

<body>
 <div id="div1" class="hello">inner text</div>
 <span id="div2" class="bye">inner text</span>
 <ol id="div3" class="goodbye">inner text</ol>
<body>

xslt:

<?xml version="1.0" encoding="UTF-8"?>


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:java="org.dita.dost.util.GenUtils" exclude-result-prefixes="java">

 <xsl:template match="*">
            <xsl:copy>
        <xsl:copy-of select="@id | @class| node()"/>
        </xsl:copy>
     </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Views: 1129

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116982

If you're only using a single template, it should be:

<xsl:template match="*">
    <xsl:copy>
        <xsl:copy-of select="@id | @class"/>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

What you have now is applied only to the body element, and it copies all its descendants as is.

Upvotes: 2

Related Questions