如何在 XSLT 中将 span 标签(或任何标签)包裹在单个单词周围?我正在使用 XSLT1,但每次尝试时似乎都卡住了。
本质上,我想传递一个段落(或一串文本):
<p>This is my text!</p>
并像这样包装每个单词,保留每个单词之间的空格和标点符号:
<p><span class="word-1">This</span> <span class="word-2">is</span> <span class="word-3">my</span> <span class="word-4">text!</span>
这主要是为了展示目的,如果有任何帮助,我将不胜感激
最佳答案
这个样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="pSeparators">
	 ,.;:?!()'"</xsl:param>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p/text()" name="tokenize">
<xsl:param name="pString" select="."/>
<xsl:param name="pMask"
select="translate(.,translate(.,$pSeparators,''),'')"/>
<xsl:param name="pCount" select="1"/>
<xsl:choose>
<xsl:when test="not($pString)"/>
<xsl:when test="$pMask">
<xsl:variable name="vSeparator"
select="substring($pMask,1,1)"/>
<xsl:variable name="vString"
select="substring-before($pString,$vSeparator)"/>
<xsl:call-template name="tokenize">
<xsl:with-param name="pString" select="$vString"/>
<xsl:with-param name="pMask"/>
<xsl:with-param name="pCount" select="$pCount"/>
</xsl:call-template>
<xsl:value-of select="$vSeparator"/>
<xsl:call-template name="tokenize">
<xsl:with-param name="pString"
select="substring-after($pString,$vSeparator)"/>
<xsl:with-param name="pMask"
select="substring($pMask,2)"/>
<xsl:with-param name="pCount"
select="$pCount + boolean($vString)"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<span class="word-{$pCount}">
<xsl:value-of select="$pString"/>
</span>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
输出:
<p><span class="word-1">This</span> <span class="word-2">is</span> <span class="word-3">my</span> <span class="word-4">text</span>!</p>
注意:通过多个分隔符进行分词。 编辑:更好的名字。将空格字符添加到分隔符序列。
关于xml - 使用 XSLT 将单词包装在标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4899901/