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.
The <xsl:apply-templates> element applies a template to the current element or to the current element's child nodes. If we add a "select" attribute to the <xsl:apply-templates> element, it will process only the child elements that matches the value of the attribute.
XSLT apply-templates define how to find elements and help in removing unwanted text in the document. It applies a template rule to the current child nodes. It adds a select attribute along with the template to specify the order of child nodes to process the current task with the help of the XSLT processor.
within a called template refers to the same node as the . in the calling template. This is not the case with apply-templates. This is the basic difference.
The xsl:apply-templates instruction selects some nodes for processing, and the template rules (between them) decide what that processing should be. This gives very loose coupling and great separation of concerns; it's rather like object-oriented message/method despatch, but much more flexible.
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!
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:
<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.<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With