在这种情况下,最简单的方法是在空格分隔符上进行拆分。如果您受限于 XSLT 1.0,最简单的方法是通过 EXSLT 库(默认情况下,在许多 XSLT 实现中可用,例如 PHP)。
您可以在此 XMLPlayground上运行以下命令(请参阅输出源)。
<!-- root -->
<xsl:template match='/'>
<example>
<xsl:apply-templates select='*' />
</example>
</xsl:template>
<!-- match sample nodes -->
<xsl:template match="example/*">
<xsl:apply-templates select='str:split(., " ")' />
</xsl:template>
<!-- match token nodes (from EXSLT split()) -->
<xsl:template match='token'>
<text><xsl:value-of select='.' /></text>
</xsl:template>
如 Playground 所示,要使用 EXSLT(前提是您可以使用它),您需要在开始xsl:stylesheet
标记中声明其命名空间。例如,要使用它的字符串库(就像我们在这里使用的那样split()
),你可以输入:
xmlns:str="http://exslt.org/strings"
extension-element-prefixes="str"
[编辑] - 如果您坚持使用子字符串方法,这是可能的,但更冗长,因为没有生成节点集的能力(这是 EXSLTsplit()
所做的),因此,在该节点集上应用模板,唯一的你包里的技巧是递归——一个模板调用自己的次数与其中的空间特征一样多。
您可以在这个(单独的)XMLPlayground上运行它
<!-- root child nodes -->
<xsl:template match='example/*'>
<xsl:call-template name='output'>
<xsl:with-param name='source' select='.' />
</xsl:call-template>
</xsl:template>
<!-- output - expects two params: -->
<!-- @output_str - the sub-string to output to a <text> node this time (has value only on self-call, i.e. recursion -->
<!-- @source - the source string on which to recurse, for more spaces in the string -->
<xsl:template name='output'>
<xsl:param name='output_str' />
<xsl:param name='source' />
<!-- output something this time? -->
<xsl:if test='$output_str'>
<text><xsl:value-of select='$output_str' /></text>
</xsl:if>
<!-- recurse... -->
<xsl:if test='$source'>
<xsl:choose>
<!-- $source contains spaces - act on the string before the next space -->
<xsl:when test='contains($source, " ")'>
<xsl:call-template name='output'>
<xsl:with-param name='output_str' select='substring-before($source, " ")' />
<xsl:with-param name='source' select='substring-after($source, " ")' />
</xsl:call-template>
</xsl:when>
<!-- source doesn't contain spaces - act on it in its entirety -->
<xsl:otherwise>
<xsl:call-template name='output'>
<xsl:with-param name='output_str' select='$source' />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>