Reputation: 11045
I have an xml like the below structure.
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
I have extracted all the title
nodes as <xsl:variable name="titles" select="/bookstore/book/title"/>
. Now, I would like to concat these titles enclosing each of them in single quotes and then separating them with commas and store them in a variable so that the output looks like: 'Harry Potter','Learning XML'
. How can I do that?
Upvotes: 2
Views: 2306
Reputation: 9627
A known list of values can be "put together" by concat()
. But in your case you do not know how many items belong to your list (in titels), the only possibility in xlst-1.0 is to iterate to the elements (for-each
or apply-templates
and concat them.
Try this:
<xsl:variable name="titles" select="/bookstore/book/title"/>
<xsl:variable name="titles_str" >
<xsl:for-each select="$titles" >
<xsl:if test="position() > 1 ">, </xsl:if>
<xsl:text>'</xsl:text>
<xsl:value-of select="."/>
<xsl:text>'</xsl:text>
</xsl:for-each>
</xsl:variable>
<xsl:value-of select="$titles_str"/>
Upvotes: 3
Reputation: 3138
You should change your titles variable with this one:
<xsl:variable name="titles">
<xsl:for-each select="/bookstore/book/title">
<xsl:text>'</xsl:text><xsl:value-of select="."/><xsl:text>'</xsl:text>
<xsl:if test="position()!=last()">, </xsl:if>
</xsl:for-each>
</xsl:variable>
to get desired output:
'Harry Potter', 'Learning XML'
Upvotes: 2