Re: [xsl] Copy Child Elements

Subject: Re: [xsl] Copy Child Elements
From: Abel Braaksma <>
Date: Sat, 26 Jan 2008 12:57:57 +0100
Alice Wei wrote:

There is one obvious problem with your XSL here:

If you are using apply-templates, what it does is that it would select any of the children of the template root. Use <xsl:apply-templates select="section"> and and <xsl:apply-templates select="//section">

I assume "and and" meant "and not" ;)
When he does that, he won't have any output left (the focus is <reference>, not <refbody>). Actually, though I agree it is usually a bad choice to use //, in his situation it doesn't change the output whether he uses // or refbody/section. However, because // is a very costly operation and it is in not necessary to use it, it should be removed.

Quoting Rick Quatro <frameexpert@xxxxxxxxxxxx>:

<xsl:template match="reference"> <xsl:apply-templates select="//section">

Change this to <xsl:apply-templates select="refbody/section" >

<xsl:template match="section"> <xsl:for-each select="p[position()&lt;=2]">

Don't use for-each here. Instead, use

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

and follow up with matching templates like the following. The last one is a so-called throw-away template, it will be called when a <p> matches that did not match any more specific match:

<xsl:template match="p[id='Field_ShowAuthorJobTitle']>
       <xsl:copy-of select="text() | *" />

<xsl:template match="p[id='Desc_ShowAuthorJobTitle']>
       <xsl:copy-of select="text() | *" />

<!-- throw away other <p> elements -->
<xsl:template match="p" />

Your own approach with xsl:if and position() is not necessarily wrong, but it is far harder to create, to maintain and to understand. Using matching templates you let the processor do the math for you.

Using copy-of instead of apply-templates in the children of <p> you make sure you copy all elements as well. Using apply-templates does only output the text value if you do not create a matching template for them (this is called an identity copy template). In your case you don't seem to need that, so copy-of suffices.

-- Abel Braaksma

Current Thread