xslt - Remove attributes or/and nodes

By xngo on June 18, 2019

<?xml version="1.0" encoding="UTF-8"?>
<!-- Remove unwanted attributes or/and nodes -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
 
    <!-- Copy everything -->
    <xsl:template match="@*|node()|text()|comment()|processing-instruction()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()|text()|comment()|processing-instruction()"/>
        </xsl:copy>
    </xsl:template>
 
    <!-- To remove attributes or nodes, simply write a matching template that doesn't do anything. Therefore, it is removed -->
    <xsl:template match="//d"/>                       <!-- Remove all d nodes -->
    <xsl:template match="//node()/node()/node()/c"/>  <!-- Remove all c nodes that have 3 ancestors -->
    <xsl:template match="@id_1"/>                     <!-- Remove all id_1 attributes -->
 
</xsl:stylesheet>

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.