0

For the image tag, I need to keep only the image file with "file/" content using XSLT in the JSON output:

My input XML file is:

<image>binary/alias/my.jpg</image>

XSL which is used as:

<xsl:template match="image">
  image: <xsl:apply-templates/>,
</xsl:template>

JSON output which I get is:

image: binary/alias/my.jpg

I need the output as:

image: files/my.jpg

Please help me on this. Thanks in advance.

zx485
  • 28,498
  • 28
  • 50
  • 59
User501
  • 319
  • 1
  • 14

2 Answers2

1

In XSLT 2.0 you can do:

<xsl:template match="image">
    <xsl:text>image: files/</xsl:text>
    <xsl:value-of select="tokenize(., '/')[last()]"/>
</xsl:template>
michael.hor257k
  • 113,275
  • 6
  • 33
  • 51
0

To get the string after the last occurrence of a char (in this case '/') you need (in XSLT-1.0) a recursive template. Applying this template, the solution is straightforward: Output the desired prefix text 'image: files/' and append the result of the recursive template:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="image">
    image: files/<xsl:call-template name="LastOccurrence">
      <xsl:with-param name="value" select="text()" />
      <xsl:with-param name="separator" select="'/'" />
    </xsl:call-template>
  </xsl:template> 

  <xsl:template name="LastOccurrence">
    <xsl:param name="value" />
    <xsl:param name="separator" select="'/'" />

    <xsl:choose>
      <xsl:when test="contains($value, $separator)">
        <xsl:call-template name="LastOccurrence">
          <xsl:with-param name="value" select="substring-after($value, $separator)" />
          <xsl:with-param name="separator" select="$separator" />
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$value" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

The LastOccurrence template was inspired by this SO post.

Community
  • 1
  • 1
zx485
  • 28,498
  • 28
  • 50
  • 59