5

Given element:

 <comments>  comments
go here
</comments>

How can I strip what may be multiple leading space characters. I cannot use normalize space because I need to retain newlines and such. XSLT 2.0 ok.

johkar
  • 435
  • 3
  • 8
  • 12

2 Answers2

4

In XPath 1.0 (means XSLT 1.0, too):

substring($input, 
          string-length(
                        substring-before($input, 
                                         substring(translate($input, ' ', ''), 
                                                   1,
                                                   1)
                                         )
                       ) +1
          )

Wrapped in an XSLT transformation:

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

 <xsl:variable name="input"
   select="string(/*/text())"/>

 <xsl:template match="/">
   '<xsl:value-of select=
   "substring($input,
              string-length(
                            substring-before($input,
                            substring(translate($input, ' ', ''),
                                      1,
                                      1)
                                             )
                            ) +1
              )
   "/>'
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following XML document:

<t>    XXX   YYY Z</t>

the correct, wanted result is produced:

   'XXX   YYY Z'
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
3

Use the replace() function:

replace($input,'^ +','')

That handles leading space characters only up to the first non-space. If you want to remove all leading whitespace characters (i.e. space, nl, cr, tab) up to the first non-whitespace, use:

replace($input,'^\s+','')
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190