Check node type in XSL template

Is it possible to check the type of node that I have mapped to a pattern inside the same pattern? In that case, how can I do this? 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> 
+6
source share
3 answers

Take a look at this answer here, as this will give you the necessary information:

The difference between: child :: node () and child :: *

This gives the following xsl: select to check all nodes, including the node document.

 <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> 
+17
source

A more accurate way to determine if node $node root of a node :

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

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

 count(.|/)=1 

but not applicable if we want to determine the type of node in a variable, which may belong to another document, and not the current document.

In addition, a test for the node namespace :

 count($node | $node/../namespace::*) = count($node/../namespace::*) 
+6
source

I highly recommend that you use expressions for the sequence types introduced in XPath 2.0 . For instance:

 . instance of document-node() . instance of element() 
+3
source

All Articles