Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove last character from xml element data

Tags:

xml

xslt

xslt-1.0

I have a xml node as below

<root>
    <element>ABC,EFG, XYZ,<element>
</root>

I want to remove last ',' from . And result should be ABC,EFG, XYZ I want to use XSL 1.0 thats kind of limitation.

XSL I am trying to use

 <xsl:template match="/">
    <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />

    <xsl:for-each select="//element">
        <xsl:if test="contains(substring(., string-length(.) - 1),$smallcase)">
            <xsl:value-of select="substring(., 1, string-length(.) - 1)"/>
        </xsl:if>
        <xsl:value-of select="substring(., string-length(.) - 1)"/>
    </xsl:for-each>
</xsl:template>
like image 592
user3138596 Avatar asked Feb 13 '23 11:02

user3138596


1 Answers

You can do this with a combination of substring and string-length:

substring(., 1, string-length(.) - 1)

I'm not sure what your current XSLT is trying to do - it will simply print the last two characters of each element element - but try something like this instead:

<xsl:template match="/">
  <xsl:apply-templates select="//element"/>
</xsl:template>

<!-- match elements whose content ends with a comma, and strip it off -->
<xsl:template match="element[substring(., string-length()) = ',']">
  <xsl:value-of select="substring(., 1, string-length(.) - 1)" />
</xsl:template>

Other element elements (ones that don't end with a comma) will be handled by the default template rules which will just print out all their text content in full.

like image 182
Ian Roberts Avatar answered Feb 16 '23 00:02

Ian Roberts