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

2019-05-29 03:35发布

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!!

标签: xslt
2条回答
贼婆χ
2楼-- · 2019-05-29 03:40

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-05-29 04:00

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

查看更多
登录 后发表回答