xml - 如何删除在 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 年)。搭建一座桥梁:与美洲印第安人社区合作的介绍
年份和左括号之间的多余空格,有人可以告诉我这个多余的空格是从哪里来的,以及如何删除它,好吗?
解决方案
原因是在</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>
,您的输出就可以了。
推荐阅读
- c# - 在 ViewModel 中将值从一个模型传递到另一个模型
- javascript - 如何将数据从 get 函数获取到 node.js 中同一个 js 文件中的另一个函数?
- ios - 哪个使用更少的内存?一个带有 5 个按钮的视图控制器,还是一个带有 5 个项目的表格视图的视图控制器?
- c# - 如何在c#中查找excel工作表每一列的行数?
- swift - 为什么这些 CAShapeLayers 没有达到预期的效果?
- php - 命名表和模型的标准方法
- python - 如何使用 guizero 指定或读取主应用程序窗口的位置?
- sas - 如何创建 MACRO 以从数据集创建 JSON 文件
- sql - SQL Server 列中的最小值
- sql - 用 Oracle 解释 PL/SQL 计划