Re: [xsl] Move leading/trailing spaces outside (XSLT 2.0)

Subject: Re: [xsl] Move leading/trailing spaces outside (XSLT 2.0)
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Tue, 06 Feb 2007 16:47:59 +0100
Yves Forkl wrote:


I want to separate the leading and trailing spaces from the rest of the content but keep them in the output as text nodes, like if I was saying in XSLT

normalize-space() won't tell me how much spaces it removed, and there must be a less awkward way than using xsl:choose with 3 clauses...

Any suggestions? Should I try with tokenize() or matches()?

Hi Yves,


Tokenize is not a good idea, because it removes the tokens. Unless you only need to count how many times there are spaces, which can be expressed as this:

count(tokenize(., '^\s+|\s+$')[not(.)])

this will return 1, 2 or 0.

matches can be used with template matching, which will give you an option to do whatever you like with it, based on whether there are trailing, leading, no, or both spaces:

<xsl:template match="e[matches(., '^\s+')]">
....<!-- do something with e-node when there are trailing spaces -->

You already saw some ways of dealing with it using analyze-string. On many occasions when you want to do something with both matching and non-matching parts, that's the best you can do.

If all you care about is replacing these spaces with some other character (like, an nbsp char) and you want to collapse consecutive spaces, there is the following you can do:

replace(., '^\s+|\s+$', 'yourspecialcharhere')

-- Abel Braaksma

Current Thread