Adrian
Adrian

Reputation: 2656

XSLT: extract filename without extension

I would like to extract file name without extension from an url:

<XML>
 <ITEM>
   <IMGURL>https://imgurl.com/1240000101.jpeg</IMGURL>
 </ITEM> 
 <ITEM>
   <IMGURL>https://imgurl.com/1255500101.jpeg</IMGURL>
 </ITEM> 
</XML>

I searched, but I found only methods for extracting filename with extension "1240000101.jpeg". I would like to output the filename only without any extension.

Example output:

1240000101
1255500101

I already tried to write this XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  
<xsl:output method="text" omit-xml-declaration="yes" />

<xsl:template match="XML">
        <xsl:for-each select="ITEM">
        <xsl:value-of select="IMGURL" />
       <xsl:text>&#xa;</xsl:text>
      </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

This extracts the whole URL. I found a working regex which captures the filename only: ([^\/]+)(?=\.\w+$), this would be great, but I don't know how to combine with code above. Can you point me to the right direction?

Upvotes: 0

Views: 1452

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117102

How about:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  
<xsl:output method="text"  />

<xsl:template match="/XML">
    <xsl:for-each select="ITEM">
        <xsl:value-of select="tokenize(IMGURL, '\.|/')[last() - 1]" />
        <xsl:text>&#xa;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Demo: http://xsltransform.hikmatu.com/94hvTyS

Upvotes: 3

Related Questions