Search code examples
xmlxsltxslt-2.0

Need to remove some text from attribute value using XSLT


I need to remove one part of text from attribute value using XSLT

XML I Used:

<img imageid="47" alt="cup." height="300" width="400" class="right" src="https://tneb.com/Services/Gets/Contents/ucr-images-v1/Images/cup-36" />

XSL I used:

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="#all">

      <xsl:template match="img">
        <xsl:element name="image">
          <xsl:attribute name="id">
            <xsl:value-of select="@imageid"/>
          </xsl:attribute>
          <xsl:attribute name="alt">
            <xsl:value-of select="@alt"/>
          </xsl:attribute>
          <xsl:attribute name="height">
            <xsl:value-of select="@height"/>
          </xsl:attribute>
          <xsl:attribute name="width">
            <xsl:value-of select="@width"/>
          </xsl:attribute>
          <xsl:attribute name="align">
            <xsl:value-of select="@class"/>
          </xsl:attribute>
          <xsl:attribute name="href">
            <xsl:value-of select="@src"/>
          </xsl:attribute>
        </xsl:element>
      </xsl:template>

 </xsl:stylesheet>

Output I get as:

 <image id="47"
 alt="cup."
 height="300"
 width="400"
 align="right"
 href="https://tneb.com/Services/Gets/Contents/ucr-images-v1/Images/cup-36"/>

Expected Output has to be:

<image id="47"
 alt="cup."
 height="300"
 width="400"
 align="right"
 href="/ucr-images-v1/Images/cup-36"/>

i need to remove some text from attribute value of image. last 3 only indicates folder structure. So i need that only itself.

Please give me any suggestion for this. Thanks in advance.


Solution

  • To get only the last 3 location steps of the path, change:

    <xsl:value-of select="@src"/>
    

    to:

    <xsl:value-of select="tokenize(@src, '/')[position() gt last() - 3]" separator="/"/>