Check type of node in XSL template

hielsnoppe picture hielsnoppe · Jan 2, 2013 · Viewed 24.1k times · Source

Is it possible to check the type of a node I matched with a template inside the same template? In case it is, how can I do it? For example I would like to do something like this:

<xsl:template match="@*|node()">
    <xsl:choose>
        <xsl:when test="current() is an attribute">
        <!-- ... -->
        </xsl:when>
        <xsl:when test="current() is an element">
        <!-- ... -->
        </xsl:when>
        <xsl:otherwise>
        <!-- ... -->
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Answer

Tim C picture Tim C · Jan 2, 2013

Take a look at this answer here, as this should give you the information you need:

Difference between: child::node() and child::*

This gives the following xsl:choose to test all the nodes, including the document node.

<xsl:choose>
  <xsl:when test="count(.|/)=1">
    <xsl:text>Root</xsl:text>
  </xsl:when>
  <xsl:when test="self::*">
    <xsl:text>Element </xsl:text>
    <xsl:value-of select="name()"/>
  </xsl:when>
  <xsl:when test="self::text()">
    <xsl:text>Text</xsl:text>
  </xsl:when>
  <xsl:when test="self::comment()">
    <xsl:text>Comment</xsl:text>
  </xsl:when>
  <xsl:when test="self::processing-instruction()">
    <xsl:text>PI</xsl:text>
  </xsl:when>
  <xsl:when test="count(.|../@*)=count(../@*)">
    <xsl:text>Attribute</xsl:text>
  </xsl:when>
</xsl:choose>