Building an XSLT String (Variable) in a Foreach Loop

The problem I came across seems simple, but as a newbie to all XSL , I have not yet found the right solution. I want to build a string by combining the results of a foreach element loop , which I can later use as a value for an attribute of an HTML element.

Given:

<?xml version="1.0" encoding="ISO-8859-1"?> <catalog> <cd> <country>UK</country> <company>CBS Records</company> </cd> <cd> <country>USA</country> <company>RCA</company> </cd> <cd> <country>UK</country> <company>Virgin records</company> </cd> </catalog> 

Required output: CBS;RCA;Virgin records

I need the real part of XSLT code that would perform this conversion in the manner described above. I believe I need an xsl variable that will contain the result of combining <company> and the separator character ; . How can this be done? Thanks.

+8
variables html xml xslt
source share
3 answers

I don’t think you can use XSL variables to concatenate, because once the value of a variable is set, it cannot be changed . Instead, I think you want something like:

 <xsl:for-each select="catalog/cd"> <xsl:choose> <xsl:when test="position() = 1"> <xsl:value-of select="country"/> </xsl:when> <xsl:otherwise> ;<xsl:value-of select="country"/> </xsl:otherwise> </xsl:choose> </xsl:for-each> 

Does that make sense to you?

Edit: I just realized, I might have misunderstood how you are going to use this variable. The above snippet can be wrapped in a variable element for later use, if you meant it:

 <xsl:variable name="VariableName"> <xsl:for-each select="catalog/cd"> <xsl:choose> <xsl:when test="position() = 1"> <xsl:value-of select="country"/> </xsl:when> <xsl:otherwise> ;<xsl:value-of select="country"/> </xsl:otherwise> </xsl:choose> </xsl:for-each> </xsl:variable> 
+10
source share

Here is one simple, true XSLT solution :

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="company"> <xsl:value-of select="."/> <xsl:if test="following::company">;</xsl:if> </xsl:template> <xsl:template match="text()"/> </xsl:stylesheet> 

When this conversion is applied to the provided XML document:

 <catalog> <cd> <country>UK</country> <company>CBS Records</company> </cd> <cd> <country>USA</country> <company>RCA</company> </cd> <cd> <country>UK</country> <company>Virgin records</company> </cd> </catalog> 

the requested, correct result (all companies combined together and separated by a symbol ; ) are created :

 CBS Records;RCA;Virgin records 
+3
source share

If you can use XSLT 2.0, then one of the following works:

Use the string-join() function:

 <xsl:variable name="companies" select="string-join(catalog/cd/company, ';')" /> 

Use @separator with xsl:value-of :

 <xsl:variable name="companies" > <xsl:value-of select="catalog/cd/company" separator=";" /> </xsl:variable> 
+3
source share

All Articles