10

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>
hielsnoppe
  • 2,819
  • 3
  • 31
  • 56
  • 1
    Tim has given a nice answer but I wonder why you need to do this inside the template and why you do not just write more specific match patterns with separate templates for the different node types. – Martin Honnen Jan 02 '13 at 09:46
  • I am interested in it for educational purposes. I am building an XSL transformation to highlight nodes that are matched by XPath expressions in an XML document. In an actual application I would not do it. – hielsnoppe Jan 02 '13 at 10:12

3 Answers3

21

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>
Community
  • 1
  • 1
Tim C
  • 70,053
  • 14
  • 74
  • 93
7

I highly recommend you to use the expressions on sequence types introduced in XPath 2.0. For example:

. instance of document-node()
. instance of element()
shapiy
  • 1,117
  • 12
  • 14
6

A more precise way to determine if the node $node is a root node:

not(count($node/ancestor::node()))

The expression in TimC's answer tests the type of the current node:

count(.|/)=1

but isn't applicable in the case when we want to determine the type of a node in a variable -- which may belong to another document -- not to the current document.

Also, a test for a namespace node:

count($node | $node/../namespace::*) = count($node/../namespace::*) 
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431