How to replace space sequences with one space but not trim in XSLT?

The function normalize-spaceremoves leading and trailing spaces and replaces sequences of whitespace with a single space. How can I only replace sequences of space characters with one space in XSLT 1.0? For example, "..x.y...\n\t..z."(spaces replaced by a period for readability) should become ".x.y.z.".

+5
source share
2 answers

Without the Becker method, you can use the discouraged character as a sign:

translate(normalize-space(concat('',.,'')),'','')

Note : three function calls ...

, :

substring(
   normalize-space(concat('.',.,'.')),
   2,
   string-length(normalize-space(concat('.',.,'.'))) - 2
)

XSLT :

<xsl:variable name="vNormalize" select="normalize-space(concat('.',.,'.'))"/>
<xsl:value-of select="susbtring($vNormalize,2,string-length($vNormalize)-2)"/>
+2

XPath 1.0:

concat(substring(' ', 1 + not(substring(.,1,1)=' ')), 
       normalize-space(), 
       substring(' ', 1 + not(substring(., string-length(.)) = ' '))
      )

, :

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="text()">
  <xsl:value-of select=
  "concat(substring(' ', 1 + not(substring(.,1,1)=' ')),
          normalize-space(),
          substring(' ', 1 + not(substring(., string-length(.)) = ' '))
          )
  "/>
 </xsl:template>
</xsl:stylesheet>

XML-:

<t>
 <t1>   xxx   yyy   zzz   </t1>
 <t2>xxx   yyy   zzz</t2>
 <t3>  xxx   yyy   zzz</t3>
 <t4>xxx   yyy   zzz  </t4>
</t>

, :

<t>
   <t1> xxx yyy zzz </t1>
   <t2>xxx yyy zzz</t2>
   <t3> xxx yyy zzz</t3>
   <t4>xxx yyy zzz </t4>
</t>
+7

All Articles