32

What's the difference between these two templates?

<xsl:template match="node()">

<xsl:template match="*">
Svish
  • 152,914
  • 173
  • 462
  • 620
  • This answer is also applicable : http://stackoverflow.com/questions/5394178/difference-between-childnode-and-child – StuartLC Aug 22 '12 at 11:10

3 Answers3

44
<xsl:template match="node()">

is an abbreviation for:

<xsl:template match="child::node()">

This matches any node type that can be selected via the child:: axis:

  • element

  • text-node

  • processing-instruction (PI) node

  • comment node.

On the other side:

<xsl:template match="*">

is an abbreviation for:

<xsl:template match="child::*">

This matches any element.

The XPath expression: someAxis::* matches any node of the primary node-type for the given axis.

For the child:: axis the primary node-type is element.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
17

Just to illustrate one of the differences, viz that * doesn't match text:

Given xml:

<A>
    Text1
    <B/>
    Text2
</A>

Matching on node()

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <!--Suppress unmatched text-->
    <xsl:template match="text()" />

    <xsl:template match="/">
        <root>
            <xsl:apply-templates />
        </root>
    </xsl:template>

    <xsl:template match="node()">
        <node>
            <xsl:copy />
        </node>
        <xsl:apply-templates />
    </xsl:template>
</xsl:stylesheet>

Gives:

<root>
    <node>
        <A />
    </node>
    <node>
        Text1
    </node>
    <node>
        <B />
    </node>
    <node>
        Text2
    </node>
</root>

Whereas matching on *:

<xsl:template match="*">
    <star>
        <xsl:copy />
    </star>
    <xsl:apply-templates />
</xsl:template>

Doesn't match the text nodes.

<root>
  <star>
    <A />
  </star>
  <star>
    <B />
  </star>
</root>
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • 3
    Nor does `*` match comment nodes, processing instruction nodes, attribute nodes, namespace nodes and document nodes... The pattern or expression `*` (on its own, as abbr. for `child::*`) **only ever matches element nodes and element nodes only**. When using `@*`, short for `attribute::*`, the asterisk matches _only_ attribute nodes on the attribute axis. – Abel Oct 07 '15 at 14:45
2

Also refer to XSL xsl:template match="/" for other match patterns.

Community
  • 1
  • 1
Peter
  • 1,786
  • 4
  • 21
  • 40