0

What is the most clean way to treat a variable that contains an empty document fragment as an empty variable?

I have the following code

<xsl:variable name="embedded-examples" select="d:example"/>

<xsl:variable name="external-examples">
    <xsl:call-template name="external-examples"/>
</xsl:variable>

<xsl:variable name="examples" select="$embedded-examples | $external-examples"/>

<xsl:if test="$examples">
    <d:section>
        <d:title>
            <xsl:text>Examples</xsl:text>
        </d:title>

        <xsl:for-each select="$examples">
            <xsl:copy-of select="."/>
        </xsl:for-each>
    </d:section>
</xsl:if>

And the template

<xsl:template name="external-examples">
    <xsl:variable name="example-comments" select="$example-docs//comment()"/>

    <xsl:for-each select="$example-comments">
        <d:example>
            <d:title><xsl:value-of select="normalize-space(.)"/></d:title>
        </d:example>
    </xsl:for-each>
</xsl:template>

The problem is that when the variable in the esternal-examples is empty the xsl:for-each loop is not run, but it produces an empty document fragment anyhow, making the test test="$examples" pass instead of fail.

What should I do in the template to make sure that when example-comments is empty the template returns nothing?

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
gioele
  • 9,748
  • 5
  • 55
  • 80

1 Answers1

0

Use a predicate to check for child nodes:

<xsl:for-each select="$example-comments[count(child::node() ) &gt; 0]">
  ...
</xsl:for-each>
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265