Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to match "none" in XSL?

Tags:

xslt

Given the following XML fragment:

<foo>
  <bar>1</bar>
  <bar>2</bar>
  <bar>3</bar>
</foo>

The following XSL should work:

<xsl:template match="/">
  <xsl:apply-templates
    mode="items"
    select="bar" />
</xsl:template>

<xsl:template mode="items" match="bar">
  <xsl:value-of select="." />
</xsl:template>

Is there a way I can use a similar format to this to apply a template when there are no <bar/> entities? For example:

<xsl:template match="/">
  <xsl:apply-templates
    mode="items"
    select="bar" />
</xsl:template>

<xsl:template mode="items" match="bar">
  <xsl:value-of select="." />
</xsl:template>

<xsl:template mode="items" match="none()">
  There are no items.
</xsl:template>
like image 792
Phillip B Oldham Avatar asked Sep 05 '25 03:09

Phillip B Oldham


2 Answers

Yes.

But the logic should be:

<xsl:template match="foo">
   <xsl:apply-templates select="bar"/>
</xsl:template>

<xsl:template match="foo[not(bar)]">
   There are no items. 
</xsl:template> 

Note: It's foo element which is having or not having bar children.

One could also use this pattern to avoid extra chooses:

<xsl:template match="/*">
    <xsl:apply-templates select="bar" mode="items"/>
    <xsl:apply-templates select="(.)[not(bar)]" mode="show-absence-message"/>
</xsl:template>

<xsl:template match="bar" mode="items">
    <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="/*" mode="show-absence-message">
    There are no items.
</xsl:template>
like image 27
Flack Avatar answered Sep 08 '25 00:09

Flack