Phillip-juan
Phillip-juan

Reputation: 546

XSL - How to do one thing if node has child, otherwise do another

I'm farely new to xslt and have tried various method to check whether a node has a child. I have the following:

<xsl:if test="child::list">

The above part works, but the problem is I have tried using when in this method with otherwise, but it does not work. It looked like so:

<xsl:when test="child::list">

which I'm guessing is wrong as it doesn't work.

The code is below:

<xsl:for-each select="td">
<td>
    <xsl:when test="child::list">
        <table cellpadding='0' cellspacing='0'>
            <thead>
                <tr>
                    <xsl:for-each select="list/item/table/thead/tr/th">
                        <th><xsl:value-of select="self::node()[text()]"/></th>
                    </xsl:for-each>
                </tr>
                <xsl:for-each select="list/item/table/tbody/tr">
                    <tr>
                        <xsl:for-each select="td">
                            <td><xsl:value-of select="self::node()[text()]"/></td>
                        </xsl:for-each>
                    </tr>
                </xsl:for-each>
            </thead>
        </table>
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="self::node()[text()]"/>
    </xsl:otherwise>
</td>
</xsl:for-each>

Any help will be appreciated...

Upvotes: 0

Views: 300

Answers (2)

JLRishe
JLRishe

Reputation: 101680

xsl:when and xsl:otherwise have to be inside of an xsl:choose:

<xsl:choose>
  <xsl:when test="...">
    <!-- Do one thing -->
  </xsl:when>
  <xsl:otherwise>
    <!-- Do something else -->
  </xsl:otherwise>
 </xsl:choose>

But what you should do here is properly utilize templates:

  <xsl:template match="something">
    ....
    <xsl:apply-templates select="td" mode="list" />
    ....
  </xsl:template>

  <xsl:template match="td" mode="list">
    <xsl:value-of select="."/>
  </xsl:template>

  <xsl:template match="td[list]" mode="list">
    <table cellpadding='0' cellspacing='0'>
      <thead>
        <xsl:apply-templates select='list/item/table/thead/tr' />
        <xsl:apply-templates select="list/item/table/tbody/tr" />
      </thead>
    </table>
  </xsl:template>

  <xsl:template match="th | td">
    <xsl:copy>
      <xsl:value-of select="." />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="tr">
    <xsl:copy>
      <xsl:apply-templates select="th | td" />
    </xsl:copy>
  </xsl:template>

Upvotes: 3

Navin Rawat
Navin Rawat

Reputation: 3138

Your created XSLT is not good. xsl:when is child element of xsl:choose which is missing in your XSLT. Please correct it first, and let us know your result.

Upvotes: 0

Related Questions