如何将span标记(或任何标记)包装在XSLT中的单个单词周围?我正在使用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>它主要是为了展示的目的,我将非常感谢任何帮助
发布于 2011-02-05 01:20:17
此样式表:
<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>注释:使用几个分隔符进行标记。编辑:更好的名称。向分隔符序列添加空格字符。
发布于 2011-02-05 00:12:40
一个简单的递归命名模板应该可以做到这一点:
<xsl:template name="wordsInTags">
<xsl:param name="text"
select="."/>
<xsl:param name="index"
select="1"/>
<xsl:choose>
<xsl:when test="contains($text, ' ')">
<span class="word-{$index}">
<xsl:value-of select="substring-before($text, ' ')"/>
</span>
<xsl:text> </xsl:text>
<xsl:call-template name="wordsInTags">
<xsl:with-param name="text">
<xsl:value-of select="substring-after($text, ' ')"/>
</xsl:with-param>
<xsl:with-param name="index">
<xsl:value-of select="$index + 1"/>
</xsl:with-param>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<span class="word-{$index}">
<xsl:value-of select="$text"/>
</span>
</xsl:otherwise>
</xsl:choose>
</xsl:template>然后简单地为需要包装单词的元素调用它:
<xsl:template match="p">
<p>
<xsl:call-template name="wordsInTags"/>
</p>
</xsl:template>很快就把它们组合在一起了,所以它可能需要更多的工作,但这应该可以让你开始。
https://stackoverflow.com/questions/4899901
复制相似问题