pubby
pubby

Reputation: 173

how to check the string length in xsl and if not upto the target length means need to replaces as space

hii every body

<Table>
    <COSTUMER_NAME>praveen</COSTUMER_NAME>
</Table>

praveen (string length) = 7

we dont know the string length of COSTUMER_NAME some times it may be less than 35 or it was be exactly 35

if the string length was less than be 35 then we need replace as space other than remaining string length part

Output: if i hv recieved string as praveen

string length was "7"

so then remaining 28 character should be replaced as space

Upvotes: 0

Views: 1527

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243529

XSLT 2.0 solution:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:my="my:my" >
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  '<xsl:sequence select=
   "my:pad(/*/*, 35, ' ')"/>'
 </xsl:template>

 <xsl:function name="my:pad" as="xs:string">
  <xsl:param name="pString" as="xs:string"/>
  <xsl:param name="pLength" as="xs:integer"/>
  <xsl:param name="pPadChar" as="xs:string"/>

  <xsl:sequence select=
   "concat($pString,
           string-join(
                   for $i in 1 to $pLength - string-length($pString)
                    return $pPadChar
                    ,
                    ''
                    )
           )
   "/>
 </xsl:function>
</xsl:stylesheet>

when applied on the provided XML document:

<Table>
    <COSTUMER_NAME>praveen</COSTUMER_NAME>
</Table>

the wanted result is produced:

  'praveen                            '

Do note:

  1. <xsl:function> is used and this ensures complete reusability.

  2. Complete parameterization gives us the most general, most applicable and most reusable solution.

  3. Such function can be defined almost exactly in the same way in XQuery or as a function item in pure XPath 3.0.

Upvotes: 0

planetjones
planetjones

Reputation: 12633

I think this should do it:

<xsl:template match="/">
    <xsl:variable name="CUSTOMER_NAME">thestring</xsl:variable>
    <xsl:value-of 
         select="substring(
                    concat(
                       $CUSTOMER_NAME,
                       '                                   '
                    ),
                    1,
                    35
                 )"/>
</xsl:template>

There are 35 white space characters there as the argument to the concat function. So it concatenates your string and 35 space characters, then takes a substring from it of the first 35 characters, so extra whitespace is lost

Upvotes: 1

Related Questions