Aaron
Aaron

Reputation: 271

XSLT 2.0: Substring-after on a for-each loop to get distinct-values

I have the following input XML:

<img src="blah.jpg"/>
<img src="blahh.jpg"/>
<img src="blah.gif"/>

I need a distinct output string of filetypes, in the format:

jpg|gif

My existing stylesheet gets some of the way:

<xsl:for-each select="distinct-values(descendant::img/@src)">
    <xsl:choose>
        <xsl:when test="position()!=last()">
            <xsl:value-of select="concat(substring-after(.,'.'),'|')"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="substring-after(.,'.')"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:for-each>

However, I get a duplicated file type because I can't put the substring-after in the for-each loop (it throws an error as you can't do a substring-after on multiple strings at once). This means I can only get distinct-values of the entire @src attribute (not the string after the period). So my output currently looks like this:

jpg|jpg|gif

I'd be really appreciative of a simple XSLT 2.0 solution that enables me to do this.

Many thanks for your time in advance - really appreciate it.

Upvotes: 2

Views: 920

Answers (1)

Tim C
Tim C

Reputation: 70648

In XSLT 2.0, you should be able to do this....

<xsl:for-each select="distinct-values(descendant::img/(substring-after(@src, '.')))">

That should return just "jpg" and "gif".

Better still, do away with the xsl:for-each altogether, and just do this

<xsl:value-of select="distinct-values(descendant::img/(substring-after(@src, '.')))" 
              separator="|" />

Of course, this assumes all your file names just have one . in. A file name like "my.file.gif" would cause issues.

Upvotes: 5

Related Questions