I am new to stackoverflow and would appreciate any help.
It is a XSLT 1.0 problem I have encountered and I’m sure there is a simple solution I just can’t find it.
I have top book element containing many chapters that each have a title:
<?xml version="1.0" encoding="utf-8"?>
<Book>
<Chapter>
<Title>ONE</Title>
</Chapter>
<Chapter>
<Title>TWO</Title>
</Chapter>
<Chapter>
<Title></Title>
</Chapter>
<Chapter>
<Title>FOUR</Title>
</Chapter>
</Book>
I want to transform the above into one element called CSV-Title-List. It seemed easy enough until the case of an empty Title occurred. I get an unexpected comma using the following stylesheet:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="Book">
<CSV-Title-List>
<xsl:for-each select="Chapter/Title">
<xsl:value-of select="."/>
<xsl:if test="position() < last()">
<xsl:text>, </xsl:text>
</xsl:if>
</xsl:for-each>
</CSV-Title-List>
</xsl:template>
</xsl:stylesheet>
My question is, how can I cleanly check the next Chapter/Title for a null string before outputting the comma with the above stylesheet. There must be a better way? Any suggestions would be appreciated. Thanks to any advice.
This transformation:
when applied on the provided XML document:
produces the wanted, correct result:
When the same transformation is applied on a different XML document — in which the first
/*/Chapter/Titlehas a white-space-only string value:again the correct, wanted result is produced: