Re: [xsl] Match DEF in ABCDEFGHIJ

Subject: Re: [xsl] Match DEF in ABCDEFGHIJ
From: Mike Brown <mike@xxxxxxxx>
Date: Thu, 17 Jul 2003 09:02:46 -0600 (MDT)
Karl J. Stubsjoen wrote:
> I'd like to match DEF in ABCDEFGHIJ...  then, I'd like to wrap some special
> HTML code around it "<strong>".

XPath provides the functions contains(), substring-before(), and 
substring-after() which you will find quite helpful. 
To highlight the first occurrence of DEF:

<xsl:variable name="substringToHighlight" select="'DEF'"/>
<xsl:if test="contains(.,$substringToHighlight)">
  <xsl:value-of select="substring-before(.,$substringToHighlight)"/>
    <xsl:value-of select="$substringToHighlight"/>
  <xsl:value-of select="substring-after(.,$substringToHighlight)"/>

If you want to highlight all occurrences of DEF, you can turn this
 into a recursive template that feeds the substring-after(...) part
to its next invocation, rather than adding it to the result tree.
If your XSLT processor detects tail recursion and optimizes for it,
it should be safe and efficient (sadly, most processors don't).

> <xsl:template name="HighlightMatches">
>   <xsl:with-param name="c" select="current()"/>
>   <xsl:with-param name="match"/>

You would use xsl:param here, not xsl:with-param.
Instead of current() you probably mean ".", but this will
work better:

<xsl:template name="HightlightMatches">
  <xsl;param name="stringToSearchIn"/>
  <xsl:param name="substringToHighlight"/>
    <xsl:when test="contains($stringToSearchIn, $substringToHighlight">
      <xsl:value-of select="substring-before($stringToSearchIn, $substringToHighlight)"/>
        <xsl:value-of select="$substringToHighlight"/>
      <xsl:call-template name="HighlightMatches">
        <xsl:with-param name="stringToSearchIn" select="substring-after($stringToSearchIn, $substringToHighlight")"/>
        <xsl:with-param name="substringToHighlight" select="$substringToHighlight"/>
      <xsl:value-of select="substring-after($stringToSearchIn, $substringToHighlight)"/>

then you can invoke it like

      <xsl:call-template name="HighlightMatches">
        <xsl:with-param name="stringToSearchIn" select="."/>
        <xsl:with-param name="substringToHighlight" select="'DEF'"/>

all untested but should be very close if not 100% correct


 XSL-List info and archive:

Current Thread