[xsl] [XSLT 1.0] Q: recursively eliminate empty nodes

Subject: [xsl] [XSLT 1.0] Q: recursively eliminate empty nodes
From: Hermann Stamm-Wilbrandt <STAMMW@xxxxxxxxxx>
Date: Mon, 8 Nov 2010 19:22:37 +0100
Hello,

I was given an identity transformation that eliminates empty nodes.
  <!-- identity template -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>
  <xsl:template match="*[not(node())]" />

I was asked on how to do this until all empty nodes are gone, even the
newly created empty nodes after removal of an inner empty node.
The question was on whether this can be done without applying the
stylesheet again and again.

I came up with below (working) "XSLT 1.0 + exslt:node-set()" solution.

The question is, whether this can be done with pure XSLT 1.0?
Especially I want to know whether it can be done without node-set()
function -- just to make sure that not every problem looks like a
nail given the exslt:node-set() hammer ...


(x.xsl one-time elimination, y.xsl recursive elimination)
http://stamm-wilbrandt.de/en/xsl-list/y.xsl

$ cat x.xml
<a><b>c<c/></b><b><c/></b></a>
$
$ xsltproc x.xsl x.xml
<?xml version="1.0" encoding="UTF-8"?>
<a><b>c</b><b/></a>
$
$ xsltproc y.xsl x.xml
<?xml version="1.0"?>
<a><b>c</b></a>
$
$ cat y.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:exslt="http://exslt.org/common";
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
>

  <!-- identity template -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>
  <xsl:template match="*[not(node())]" />

  <!-- recursive template -->
  <xsl:template name="elimininateEmptyNodes">
    <xsl:param name="elem"/>
    <xsl:choose>
      <xsl:when test="$elem//*[not(node())]">
        <xsl:variable name="aux">
          <xsl:apply-templates select="$elem/*"/>
        </xsl:variable>
        <xsl:call-template name="elimininateEmptyNodes">
          <xsl:with-param name="elem" select="exslt:node-set($aux)"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:copy-of select="$elem"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="/">
    <xsl:call-template name="elimininateEmptyNodes">
      <xsl:with-param name="elem" select="/"/>
    </xsl:call-template>
  </xsl:template>

</xsl:stylesheet>
$


Mit besten Gruessen / Best wishes,

Hermann Stamm-Wilbrandt
Developer, XML Compiler, L3
Fixpack team lead
WebSphere DataPower SOA Appliances
----------------------------------------------------------------------
IBM Deutschland Research & Development GmbH
Vorsitzender des Aufsichtsrats: Martin Jetter
Geschaeftsfuehrung: Dirk Wittkopp
Sitz der Gesellschaft: Boeblingen
Registergericht: Amtsgericht Stuttgart, HRB 243294

Current Thread