Re: [xsl] newbie xsl apply-templates nesting question

Subject: Re: [xsl] newbie xsl apply-templates nesting question
From: Wendell Piez <wapiez@xxxxxxxxxxxxxxxx>
Date: Mon, 07 Jan 2008 17:53:02 -0500

At 05:39 PM 1/7/2008, you wrote:
let's say i have some XML like this

  <p>this is plain <span class="underline">and this is underlined</span>
and this is plain again</p>

and my stylesheet looks like this:

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

<xsl:template match="p">
  <xsl:apply-templates select="span[@class='underline']"/>
  <fo:block><xsl:value-of select="."/><fo:block>

<xsl:template match="span[@class='underline']">
  <fo:inline text-decoration="underline"><xsl:vaue-of

as you probably can guess, the underlined text comes up first, then the
plain text comes next. i have a feeling i'm misunderstanding something
very fundamental here.

Yes: what you want is somewhat simpler:

<xsl:template match="p">

Not only is this simpler, but it will remain simple as the complexity of your input grows (say you get other sorts of content besides span elements inside your p elements).

What you are missing is how the contents of a template rule indicate literally what goes into the output. Inside your p, you do not want (first) the results of processing your span children, and (then) a block containing the string value of the p. Rather, you want simply a block, containing the results of processing all the children of the p, in document order, including text and whatever other elements may be there. Ordinarily, XSLT processes nodes by applying templates to them, so we say "apply-templates", and by default all the child nodes are selected, and their results spliced together in order reflecting the input.

The explicit and long-form syntax for <xsl:apply-templates/> is <xsl:apply-templates select="child::node()"/>, but you have to go to XSLT School to learn that.

It also helps to know that there are built-in template rules to match nodes for which you have not written any of your own -- and that the built-in rule for text nodes says "copy this out", while the built in rule for elements says "keep going down the tree". If you don't know those rules are there, things can be very mysterious. But if you learn to trust them they will keep you aloft.

These days I am recommending Evan Lenz's little Pocket Reference for XSLT (O'Reilly), which devotes several sweet pages to the XSLT processing model. That's what you have to master.


Wendell Piez                            mailto:wapiez@xxxxxxxxxxxxxxxx
Mulberry Technologies, Inc.      
17 West Jefferson Street                    Direct Phone: 301/315-9635
Suite 207                                          Phone: 301/315-9631
Rockville, MD  20850                                 Fax: 301/315-8285
  Mulberry Technologies: A Consultancy Specializing in SGML and XML

Current Thread