Removing all blanks from a string

Here should go questions about transforming XML with XSLT and FOP.
alk
Posts: 32
Joined: Wed Jan 25, 2006 5:43 pm

Removing all blanks from a string

Post by alk »

Hi there,

maybe I'm thinking much to complicated, but all I want to do is to remove all blanks from a string and assign the result to variable. In an act of desperation I created the following function:

Code: Select all


	<xsl:function name="str:strip-blanks" as="xs:string">
<xsl:param name="myparam" as="xs:string"/>
<xsl:analyze-string regex="\S+" select="$myparam">
<xsl:matching-substring>
<xsl:value-of select="."/>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:function>
But when running my script I receive the message 'A sequence of more than one item is not allowed as result of function str:strip-blanks()'.

Any ideas on this or is there a much simpler solution???

Best regards
- alex
george
Site Admin
Posts: 2095
Joined: Thu Jan 09, 2003 2:58 pm

Post by george »

Hi Alex,

In general this can be performed with a string normalization to have all kind of whitespace characters converted to space followed by a translate of space to nothing:

Code: Select all


translate(normalize-space($myParam), ' ', '')
Note that the above works also in XSLT 1.0.

Best Regards,
George
alk
Posts: 32
Joined: Wed Jan 25, 2006 5:43 pm

Post by alk »

Hi George,

what can I say? Hail to the king! Thanks a lot for this damned fast answer... and it works... as always!

Just one thing. Do you have any idea what's causing my error message? Pure curiosity...

Best Regards
- alex
george
Site Admin
Posts: 2095
Joined: Thu Jan 09, 2003 2:58 pm

Post by george »

Hi Alex,

If you have more than one match then the xsl:matching-string will be activated more than once and the value-of will generate more than one item. Now you declared the expected result of the funtion to be one string value thus the error. If you change that to string* for instance then you will not have this error anymore but the result will be a sequence of strings rather than a string. Alternatively you can get the sequence inside the function in a variable and then concat the sequence items for return:

Code: Select all


<xsl:function name="str:strip-blanks" as="xs:string">
<xsl:param name="myparam" as="xs:string"/>
<xsl:variable name="content">
<xsl:analyze-string regex="\S+" select="$myparam">
<xsl:matching-substring>
<xsl:value-of select="."/>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:variable>
<xsl:value-of select="concat($content, '')"/>
</xsl:function>
Best Regards,
George
Post Reply