Skip to content

Instantly share code, notes, and snippets.

@cpburnz
Last active May 19, 2016 13:30
Show Gist options
  • Save cpburnz/6cc05c4a0ea4d66e875ccbebbd6eda4a to your computer and use it in GitHub Desktop.
Save cpburnz/6cc05c4a0ea4d66e875ccbebbd6eda4a to your computer and use it in GitHub Desktop.
Remove Attribute from Elements using XSLT
<?xml version="1.0"?>
<root>
<parent>
<child id="a" value="true"/>
<child id="b" value="true"/>
<child id="c" value="true"/>
</parent>
</root>
<?xml version="1.0"?>
<root>
<parent>
<child id="a"/>
<child id="b"/>
<child id="c" value="true"/>
</parent>
</root>
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common">
<!-- Remove from specified children. -->
<xsl:variable name="remove">
<child id="a"/>
<child id="b"/>
</xsl:variable>
<!-- Match "value" attribute. -->
<xsl:template match="/root/parent/child/@value">
<!-- Get child ID. -->
<xsl:variable name="id" select="current()/parent::node()/@id"/>
<!-- If there is no match, keep value; otherwise, remove value. -->
<xsl:if test="not(exsl:node-set($remove)/*[@id = $id])">
<xsl:copy/>
</xsl:if>
</xsl:template>
<!-- Copy all nodes and attributes unless another rule indicates otherwise. -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

XSLT Remove Attribute from Elements

Transform XML document:

xsltproc -o output.xml remove-attribute.xslt input.xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment