首页 > 解决方案 > 如何删除在 XSLT 中应用模板时产生的额外空间?

问题描述

我有这个 XML 文件:

<mixed-citation >
    <collab>American Indian Research and Policy Institute.</collab>
    (<year>2000</year>).
    <source>
        <bold>To build a bridge: An introduction to working with American Indian communities</bold>
    </source>
</mixed-citation>

我有这个 XSL:

<xsl:template match="mixed-citation">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="year">
    <span class="references__{name()}">
        <xsl:apply-templates/>
    </span>
</xsl:template>


<xsl:template match="source">
    <span class="references__{name()}">
        <strong>
            <xsl:value-of select="."/>
        </strong>
    </span>
</xsl:template>

问题是当应用这个 XSLT 规则时,结果会产生额外的空间,我不知道它来自哪里,结果如下:

美国印第安人研究与政策研究所(2000 年)。搭建一座桥梁:与美洲印第安人社区合作的介绍

年份和左括号之间的多余空格,有人可以告诉我这个多余的空格是从哪里来的,以及如何删除它,好吗?

标签: xmlxsltxpath

解决方案


原因是在</collab>您的源 XML 实际上包含一个文本节点之后,其中包含一个换行符、4 个空格和( (以及之后的year元素)。

这些“不可见”字符在 HTML 中呈现为单个空格。

一种可能的解决方案是添加模板匹配text()并使用剥离的初始/终端“白色”字符生成输出:

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

实际上,normalize-space()还将文本节点中间的每个“白色”字符序列更改为单个空格。

也许您还应该<xsl:strip-space elements="*"/> 在 XSLT 脚本的开头添加(实际上是在 之后xsl:output)。

但请注意,此更改还将删除bridge:An Introduction...之间的空格。

要保留此空间,您必须明确添加它。只需在<xsl:text> </xsl:text>之前添加<strong> ,您的输出就可以了。


推荐阅读