Reputation: 671
I'm trying to create an dropdown element in an XSLT where the value and label is separated by a colon (:) and a newline for the next item.
1st I have a plain xml like; (system generated)
<root>
<item>
test1 : Test 1
test2 : Test 2
test3 : Test 3
</item>
</root>
then I split it to:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text/text()" name="tokenize">
<xsl:param name="text" select="."/>
<xsl:param name="separator" select="'
'"/>
<xsl:choose>
<xsl:when test="not(contains($text, $separator))">
<item><xsl:value-of select="normalize-space($text)"/></item>
</xsl:when>
<xsl:otherwise>
<item>
<xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
</item>
<xsl:call-template name="tokenize">
<xsl:with-param name="text" select="substring-after($text, $separator)"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Output:
<root>
<text>
<item>test1 : Test 1</item>
<item>test2 : Test 2</item>
<item>test3 : Test 3</item>
</text>
</root>
Then I don't know what's next? Is it possible to create a second template to create the html select?
<select>
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test3">Test 3</option>
</select>
Please helppppp.... :'(
Upvotes: 0
Views: 317
Reputation: 117073
Well, if you change your stylesheet to something like:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="item">
<select>
<xsl:call-template name="tokenize">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
</select>
</xsl:template>
<xsl:template name="tokenize">
<xsl:param name="text"/>
<xsl:param name="delimiter" select="' '"/>
<xsl:variable name="token" select="substring-before(concat($text, $delimiter), $delimiter)" />
<xsl:if test="$token">
<option value="{substring-before($token, ' : ')}">
<xsl:value-of select="substring-after($token, ' : ')"/>
</option>
</xsl:if>
<xsl:if test="contains($text, $delimiter)">
<!-- recursive call -->
<xsl:call-template name="tokenize">
<xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
you will receive:
<html>
<body>
<select>
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test3">Test 3</option>
</select>
</body>
</html>
Upvotes: 1