How do I replace sequences of whitespaces by one space but don't trim in XSLT?
The function normalize-space
removes leading and trailing whitespace and replaces sequences of whitespace characters by a single space. How can I only replaces sequences of whitespace characters by a single space in XSLT 1.0? For instance "..x.y...\n\t..z."
(space开发者_如何学JAVAs replaced by a dot for readability) should become ".x.y.z."
.
Use this XPath 1.0 expression:
concat(substring(' ', 1 + not(substring(.,1,1)=' ')),
normalize-space(),
substring(' ', 1 + not(substring(., string-length(.)) = ' '))
)
To verify this, the following transformation:
<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>
when applied on this XML document:
<t>
<t1> xxx yyy zzz </t1>
<t2>xxx yyy zzz</t2>
<t3> xxx yyy zzz</t3>
<t4>xxx yyy zzz </t4>
</t>
produces the wanted, correct result:
<t>
<t1> xxx yyy zzz </t1>
<t2>xxx yyy zzz</t2>
<t3> xxx yyy zzz</t3>
<t4>xxx yyy zzz </t4>
</t>
Without Becker's method, you could use some discouraged character as mark:
translate(normalize-space(concat('',.,'')),'','')
Note: Three function calls...
Or with any character but repeating some expression:
substring(
normalize-space(concat('.',.,'.')),
2,
string-length(normalize-space(concat('.',.,'.'))) - 2
)
In XSLT you can easily declare a variable:
<xsl:variable name="vNormalize" select="normalize-space(concat('.',.,'.'))"/>
<xsl:value-of select="susbtring($vNormalize,2,string-length($vNormalize)-2)"/>
精彩评论