为什么normalize-space()不会剥离所有空格?

时间:2016-02-27 22:27:33

标签: xml xslt removing-whitespace

我写了一个小XSLT,其中我添加了normalize-space()函数来删除不必要的空格:

http://xsltransform.net/bnnZWM

<xsl:template match="page/pageFunctionResult/*/text()">
   <xsl:value-of select="normalize-space(.)"/>
</xsl:template>

XSLT本身有效,除了一些空格没有规范化:

<category> TEST </category>

我不明白为什么normalize-space()无法删除这些空格。

2 个答案:

答案 0 :(得分:6)

如评论中所述,这些角色实际上是非破坏性的空间角色(#160)。要将它们作为常规空格处理,请使用:

<xsl:value-of select="normalize-space(translate(., '&#160;', ' '))"/>

答案 1 :(得分:4)

normalize-space()功能条whitespace

[3]       S      ::=      (#x20 | #x9 | #xD | #xA)+

您链接的示例中TEXT周围的字符其中一个字符(在评论中指出@ har07)。 Per @ michael.hor257k的clever use of string-to-codepoints()

<xsl:template match="page/pageFunctionResult[1]/category[1]">
  <xsl:value-of select="string-to-codepoints(substring(., 1, 1))"/>
</xsl:template>

我们可以看到它们是NO-BREAK SPACE个字符(#xA0),又名&nbsp;

要删除&nbsp;,您需要的内容超过normalize-space() ....

XSLT 1.0

See @michael.hor257k's answer.(+1)

XSLT 2.0

如果您想要涵盖&nbsp;以及其他类型的空白字符,请在replace()之前使用normalize-space() category escape

<xsl:value-of select="normalize-space(replace(., '\p{Z}', ' '))"/>