Re: [xsl] select="substring-before($str,"'")" !!!

Subject: Re: [xsl] select="substring-before($str,"'")" !!!
From: Jeni Tennison <mail@xxxxxxxxxxxxxxxx>
Date: Tue, 16 Jan 2001 13:51:54 +0000
Hi Phil,

Within an attribute value, &apos; gives you an apostrophe and &quot;
gives you a double-quote.  The XPath interpreter sees the value of the
attribute after all the &apos;es have been exchanged for 's and the
&quot;s for "s.  So:

  substring-before($str, "'")

could be written:

  substring-before($str, &quot;&apos;&quot;)

You only *have* to escape the quotes or apostrophes that you use
around the attribute value, so if you use double quotes, then do
something like:

  select="substring-before($str, &quot;'&quot;)"


  select='substring-before($str, "&apos;")'

Just a quick other comment: Did you know that you can use the 'select'
attribute on xsl:variable, xsl:param and xsl:with-param rather than
use the content and xsl:value-of? For example, your template:

>   <xsl:template name="escape-string-for-javascript">
>     <xsl:param name="str"/>
>     <xsl:choose>
>       <xsl:when test="contains($str,"'")">
>         <xsl:variable name="before-first-apostrophe"><xsl:value-of select="substring-before($str,"'")"/></xsl:variable>
>         <xsl:variable name="after-first-apostrophe"><xsl:value-of select="substring-after($str,"'")"/></xsl:variable>
>         <xsl:value-of select="$before-first-apostrophe"/>\'<xsl:call-template name="escape-string-for-javascript"><xsl:with-param name="str"><xsl:value-of
> select="$after-first-apostrophe"></xsl:with-param></xsl:call-template>
>       </xsl:when>
>       <xsl:otherwise>
>         <xsl:value-of select="$str">
>       </xsl:otherwise>
>     </xsl:choose>
>   </xsl:template>

could be written:

   <xsl:template name="escape-string-for-javascript">
     <xsl:param name="str"/>
       <xsl:when test='contains($str,"&apos;")'>
         <xsl:variable name="before-first-apostrophe"
         <xsl:variable name="after-first-apostrophe"
         <xsl:value-of select="$before-first-apostrophe"/>\'<xsl:text/>
         <xsl:call-template name="escape-string-for-javascript">
            <xsl:with-param name="str" select="$after-first-apostrophe" />
         <xsl:value-of select="$str">

and called like:

document.writeln('<xsl:call-template name="escape-string-for-javascript">
                     <xsl:with-param name="str" select="name"/>

Using the 'select' attribute is usually better, if you can get away
with it, because it doesn't build a result tree fragment as the
variable value, but uses a string, number, boolean or node-set.  That
generally means it's more efficient and doesn't react in strange and
confusing ways to boolean tests (for example).

I hope that helps,


Jeni Tennison

 XSL-List info and archive:

Current Thread