text - XSLT - extract a string within brackets -


i have node

<example>       test1 (10) test2 (20) ...  </example> 

and need transform to:

<example>       test1 <number>10</number> test2 <number>(20)</number> </example> 

therefore need function extract text between ( , ) recursively. bad news need in xslt version 1.0.

you can use recursive template called name following. note recursive templates can problematic if recursion depth high. if input text contains couple of thousand parens, it's possible xslt processor crashes stack overflow. these errors extremely hard debug. if you're dealing handful of parens, recursive approach should ok.

also note example doesn't handle nested parens.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform">  <xsl:template match="example">     <xsl:copy>         <xsl:call-template name="convert-parens">             <xsl:with-param name="string" select="."/>         </xsl:call-template>     </xsl:copy> </xsl:template>  <xsl:template name="convert-parens">     <xsl:param name="string"/>      <xsl:choose>         <xsl:when test="contains($string, '(')">             <xsl:variable name="after" select="substring-after($string, '(')"/>             <xsl:choose>                 <xsl:when test="contains($after, ')')">                     <xsl:value-of select="substring-before($string, '(')"/>                     <number>                         <xsl:value-of select="substring-before($after, ')')"/>                     </number>                     <xsl:call-template name="convert-parens">                         <xsl:with-param name="string" select="substring-after($after, ')')"/>                     </xsl:call-template>                 </xsl:when>                 <xsl:otherwise>                     <xsl:value-of select="$string"/>                 </xsl:otherwise>             </xsl:choose>         </xsl:when>         <xsl:otherwise>             <xsl:value-of select="$string"/>         </xsl:otherwise>     </xsl:choose> </xsl:template>  </xsl:stylesheet> 

Comments