Re: [xsl] Can a single XPath statement duplicate the functionality of this verbose <xsl:choose> statement?

Subject: Re: [xsl] Can a single XPath statement duplicate the functionality of this verbose <xsl:choose> statement?
From: Andrew Welch <andrew.j.welch@xxxxxxxxx>
Date: Mon, 24 Oct 2011 12:40:52 +0100
On 24 October 2011 12:06, Mark <mark@xxxxxxxxxxxx> wrote:
> Hi Andrew,
> All of your recommendations made sense to me except this one:
>
> - instead of xsl:value-of use xsl:apply-templates
>
> I have been seeing "value-of" as a kind of "literal print" into the result
> document. How could "apply-templates" be substituted for it?

xsl:value-of will create a text node in the result tree,
xsl:apply-templates will ultimately apply templates on the text node
where the default template will kick in and copy it to the result
tree... so the effect is the same, however in the latter case you are
making it available for overriding.

so for example:

<drink type="beer"/>

you could do:

<xsl:template match="drink">
  <div>Drink type: <xsl:value-of select="@type"/></div>
</xsl:template>

or you could do:

<xsl:template match="drink">
  <div>Drink type: <xsl:apply-templates select="@type"/></div>
</xsl:template>

both will output the same result.

Now if a requirement comes in to wrap the type in <b>, but only if its
'beer', if you have used apply-templates you can just add the
template:

<xsl:template match="@type[. = 'beer']">
  <b><xsl:next-match/></b>
</xsl:template>

...and then go home.   However if you have use value-of earlier on,
you would need to go and modify that template first to change it to an
apply-templates anyway.

Regarding the "literal print" aspect, a key point to get early on is
that a transform is where the xml is parsed into a tree, the
xml-that-is-the-xslt is parsed into a tree (both using the xml
parser), the xslt processor then runs the transform to create the
result tree, which a serializer then runs over to create the string
that you see as output.  The main concept is that your stylesheet adds
nodes to a result tree - xsl:value-of adds a text node to the result
tree, you aren't constructing a string.  Its only when the result tree
is serialized that text node becomes a string.

For example, the result tree might contain a node named "br", if that
gets serialized as xml the output will be <br/>, if its serialized as
xhtml it will be <br></br> and for html it will be <br>... the point
is it's the same node in the result tree - your transform creates that
node in the result tree - which the serializer then turns into the
output string.






-- 
Andrew Welch
http://andrewjwelch.com

Current Thread