joe
joe

Reputation: 17488

What is the difference between <xsl:apply-templates /> and <xsl:apply-templates select="." />

What is the difference between <xsl:apply-templates /> and <xsl:apply-templates select="." />. I thought that the select="." was not necessary, but I am getting different results depending on which I use.

Sorry if this is a repeat. I have tried searching this issue but could not find anything.

Upvotes: 8

Views: 2158

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243579

What is the difference between <xsl:apply-templates /> and <xsl:apply-templates select="." />

The first instruction:

<xsl:apply-templates />

is a shorthand for:

<xsl:apply-templates select="child::node()" />

The second instruction:

<xsl:apply-templates select="." />

is a shorthand for:

<xsl:apply-templates select="self::node()" />

As we see, not only these two instructions are different (the former applies templates to all child nodes and the latter applies templates to the current node), but the latter is dangerous and often may lead to an endless loop!

Upvotes: 18

LarsH
LarsH

Reputation: 28004

Were you thinking of the difference between

<xsl:apply-templates />

and

<xsl:apply-templates select="*" />

? The reason I ask is that <xsl:apply-templates select="." /> is very uncommon, while <xsl:apply-templates select="*" /> is very common.

When choosing between these two alternatives, select="*" is often unnecessary, but there is a difference:

  • As Dimitre pointed out, <xsl:apply-templates /> without a select will process all child nodes. This includes comments, processing instructions, and most notably, text nodes, as well as child elements.
  • By contrast, <xsl:apply-templates select="*" /> will only select child element nodes.

So if the input XML can have child nodes other than elements, and you don't want to process those nodes, <xsl:apply-templates select="*" /> is what you want.

Upvotes: 4

Related Questions