Punter Vicky Punter Vicky - 1 month ago 21
Java Question

XSLT - removing empty nodes

I am using the below xslt to remove namespaces. How can it be enhanced to remove empty tags as well?

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />

<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>


</xsl:stylesheet>

Answer

You can strip any empty elements as follows:

<xsl:template match="*[not(normalize-space())]"/>

Also you strip-namespaces template does not account for attributes, so you may want to extend it as follows:

<xsl:template match="*">
<xsl:element name="{local-name()}">
  <xsl:for-each select="@*">
    <xsl:attribute name="{local-name()}">
      <xsl:value-of select="."/>
    </xsl:attribute>
  </xsl:for-each>
  <xsl:apply-templates/>
</xsl:element>
</xsl:template>
Comments