Reputation: 2066
I have a variable $colors that is a string
<xsl:variable name="colors" select="'red,green,blue,'" />
I need a new variable, $colorElements that is a node-set
<color>red</color>
<color>green</color>
<color>blue</color>
(Is that right? Can a node-set have no root?)
$colorElements
will never be output directly. I just need it as, effectively, a list variable.
XSLT 1.0 with no extensions other than node-set()
.
Upvotes: 3
Views: 6705
Reputation: 12729
How about this?:
<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:output method="xml" indent="yes" encoding="utf-8" />
<xsl:variable name="colors" select="'red,green,blue,'" />
<xsl:template match="/" name="main">
<csv-to-xml>
<xsl:for-each select="tokenize($colors, ',')[position()!=last()]">
<!-- The predicate is needed because of the extraneous comma
at the end of the red,green,blue, list. -->
<color><xsl:value-of select="." /></color>
</xsl:for-each>
</csv-to-xml>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1
Reputation: 56222
Use:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="colors" select="'red,green,blue,'" />
<xsl:template match="/">
<xsl:variable name="colorElements">
<xsl:call-template name="split">
<xsl:with-param name="pText" select="$colors"/>
</xsl:call-template>
</xsl:variable>
<xsl:for-each select="msxsl:node-set($colorElements)">
<xsl:copy-of select="color"/>
</xsl:for-each>
</xsl:template>
<xsl:template name="split">
<xsl:param name="pText"/>
<xsl:variable name="separator">,</xsl:variable>
<xsl:choose>
<xsl:when test="string-length($pText) = 0"/>
<xsl:when test="contains($pText, $separator)">
<color>
<xsl:value-of select="substring-before($pText, $separator)"/>
</color>
<xsl:call-template name="split">
<xsl:with-param name="pText" select="substring-after($pText, $separator)"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<color>
<xsl:value-of select="$pText"/>
</color>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Upvotes: 3