<xsl:preserve-space> 元素

保留 elements 属性所指定的元素中可能出现的纯空白文本节点。

<xsl:preserve-space
  elements = tokens />

特性

  • 元素
    这是必选的属性。值为通过空白分隔的节点名称标记列表,这些节点必须保留纯空白文本节点。

元素信息

出现次数

无限制

父元素

xsl:stylesheetxsl:transform

子元素

(无子元素)

注释

<xsl:preserve-space> 元素保留指定元素中的纯空白文本节点。对同时包含空白字符和非空白字符的文本节点中的空白字符没有影响。此处保留纯空白文本节点意味着源文档中的节点在结果文档中将保留。<xsl:strip-space> 则相反;它去除指定节点中的纯空白文本节点。

默认情况下,将保留所有纯空白文本节点。如果元素名与 <xsl:strip-space> 元素中的名称测试匹配,将从保留空白的元素名集合中删除。如果元素名与 <xsl:preserve-space> 元素中的名称测试匹配,将添加回保留空白的元素名集合。

有关更多信息,请参见 www.w3.org/TR/xslt 上 XSLT W3 Recommendation 的第 3.4 节“Whitespace Stripping”。

示例

以下示例阐释使用 <xsl:preserve-space> 和 <xsl:strip-space> 保留和去除纯空白文本节点的效果。

XML 文件 (source.xml)

<?xml version="1.0"?>
<document>
<text>   </text>
<text>  ;</text>
<text>
This is a   sample text 
    
</text>
<code>   </code>
<code>  ;</code>
<code>
This is a   sample code 
    
</code>
</document>

XSLT 文件 (trans.xsl)

<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <!-- 
     The following xsl:preserve-space is not necessary.
     It is included to emphasize the fact that white-space-only
     text nodes are to be preserved on the <code> elements.
   -->
  <xsl:preserve-space elements="code"/>
  <xsl:strip-space elements="text"/>

  <xsl:template match="/">
    code elements:
    <xsl:apply-templates select="//code"/>

    text elements:
    <xsl:apply-templates select="//text"/>
  </xsl:template>

  <xsl:template match="text">
     text # <xsl:value-of select="position()"/>
     has <xsl:value-of select="count(text())"/> text(). 
     "<xsl:value-of select="translate(.,' &#10;&#13;&#9;', '-NRT')"/>"
  </xsl:template>


  <xsl:template match="code">
     code # <xsl:value-of select="position()"/>
     has <xsl:value-of select="count(text())"/> text(). 
     "<xsl:value-of select="translate(.,' &#10;&#13;&#9;', '-NRT')"/>"
  </xsl:template>

</xsl:stylesheet>

尝试一下!

  1. 复制上面的代码并将其保存到本地驱动器中适当的文件中。

  2. 启动 XSLT 转换,在命令提示下使用“命令行转换实用工具”(Command Line Transformation Utility) (msxsl.exe),方法如下:

    msxsl source.xml trans.xsl

    重要

    不要从 Internet Explorer 启动转换。浏览器执行某些不符合 XSLT 规范的去除空格操作。这可能造成 XLST 转换执行异常。

输出

以下是标准输出:

code elements:

code # 1

has 1 text().

"---"

code # 2

has 1 text().

"--;"

code # 3

has 1 text().

"NThis-is-a-Tsample-codeTNTN"

text elements:

text # 1

has 0 text().

""

text # 2

has 1 text().

"--;"

text # 3

has 1 text().

"NThis-is-a-Tsample-textTNTN"

请注意,该转换为第一个 <code> 元素生成一个文本节点,而不会为第一个 <text> 元素生成文本节点。这是因为这两个元素均具有一个这样的纯空白文本节点,根据样式表开头列出的 <xsl:preserve-space> 和 <xsl:strip-space> 指令,该节点在 <code> 中保留,而在 <text> 中去除。每种类型中的第二个和第三个元素显示,非纯空白文本节点不受这些指令的影响。

请参阅

参考

<xsl:strip-space> 元素