Re: [xsl] Explanation of mode?

Subject: Re: [xsl] Explanation of mode?
From: "Jon Gorman" <jonathan.gorman@xxxxxxxxx>
Date: Mon, 20 Feb 2006 09:28:03 -0600
A quick example might help, although I'm not sure where the confusion
is.  Let's say that when title appears in the citations at the end of
a paper we want it to appear differently than when it appears in the
text of an article.

quick and dirty xml sample

<title>Sheep, Sleep, and Code</title>
<p>In the landmark paper <title citeid="bly02a">Foo, Bar, and
Myself<title> Marklovitic proposes...</p>
<!-- some more paragraphs here-->
<cite><author>Marklovitic, A.</author> <title id="bly02a">Marklovitic</title>

One approach to displaying the three title elements differently could
be to use an XPath with the parent element, that have three templates

<xsl:template match="head/title"> <!-- some stuff here --></xsl:template>
<xsl:template match="cite/title"> <!-- some stuff here --></xsl:template>
<xsl:template match="title"> <!-- this would match any title that is
not in a head/title, cite/title --></xsl:template>

Of course, notice in this case this works because two of the places
where title occured consistently at the same depth.  What if you had
no control of how deep title occurred in the cite element.  Say
perhaps there could be an element titleinfo, containing sub-elements
popular title and actual title.
<cite><titleinfo><poptitle>Cormen</poptitle><title>Introduction to

One solution to this problem is to use modes.

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

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

<xsl:template match="title" mode="head">
<h1><xsl:value-of select="."></h1>

<xsl:template match="title" mode="cites">
<a name="#{@id}" />
<xsl:text>"</xsl:text><xsl:value-of select="."><xsl:text>"</xsl:text>

<xsl:template match="title">
<a class="cite" href="#{@citeid}"><xsl:value-of select="." /></a>

Notice here we're also relying on the built-in template mode described
in section 5.8 of the specs (XSLT 1.0, not XSLT 2.0).  That means
there is a default template that will match an element in the
particular mode that just recurses down the tree.  So in this simple
stylesheet, it would match titleinfo and do a <xsl:apply-templates
mode="cites" /> automatically.

Don't know if that is of any help.  Might be better if you gave a
better idea of what's you are having trouble with.

Jon Gorman

Current Thread