How to remove spaces from the end of text in an el

2019-05-29 03:50发布

问题:

Does anyone know what XSL code would remove the trailing whitespace after the last word in an element?

<p>This is my paragraph.  </p>

Thanks!!

回答1:

Look at the normalize-space() XPath function.

<xsl:template match="p">
  <p><xsl:value-of select="normalize-space()" /></p>
</xsl:template>

Be careful, there is a catch (which might or might not be relevant to you):

The [...] function returns the argument string with whitespace normalized by stripping leading and trailing whitespace and replacing sequences of whitespace characters by a single space.

This means it also removes all line breaks and tabs and other whitespace and turns them into a single space.



回答2:

EDIT: Significant simplification of the code, thanks to a hint from Tomalak.

Here is an XPath 2.0 / XSLT 2.0 solution, which removes only the trailing spaces:

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

  <xsl:template match="text()">
    "<xsl:sequence select="replace(., '\s+$', '', 'm')"/>"
  </xsl:template>
</xsl:stylesheet>

When this is applied on the following XML document:

<someText>   This is    some text       </someText>

the wanted result is produced:

"   This is    some text"

You can see the XSLT 1.0 solution (implementing almost the same idea), which uses FXSL 1.x, here:

http://www.biglist.com/lists/xsl-list/archives/200112/msg01067.html



标签: xslt