Reputation: 65
I have a node
<example>
Test1 (10) test2 (20) ...
</example>
And i need to transform this to:
<example>
Test1 <number>10</number> test2 <number>(20)</number>
</example>
Therefore i need a function that will extract all the text between ( and ) recursively. The bad news is that i need it in XSLT version 1.0.
Upvotes: 0
Views: 1824
Reputation: 100
With a xsl:analyze-string with a regex, the code can be more simple:
<xsl:template match="example">
<element>
<xsl:analyze-string select="text()" regex="[(][0-9][0-9][)]">
<xsl:matching-substring>
<number>
<xsl:value-of select="substring(.,2,2)"/>
</number>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</element>
</xsl:template>
Upvotes: 0
Reputation: 33658
You can use a recursive template called by name like the following. Note that recursive templates can be problematic if the recursion depth is too high. If your input text contains a couple of thousand parens, it's possible that the XSLT processor crashes with a stack overflow. These errors are extremely hard to debug. If you're only dealing with a handful of parens, the recursive approach should be OK.
Also note that my 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>
Upvotes: 1