这是一个 XSLT 2.0 转换,它将单词分成两行,以便第一行不超过预定义的长度:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:param name="pMaxLength" select="15"/>
<xsl:template match="ELEMENT">
<xsl:variable name="vWords" select="tokenize(@attribute, '\W+')"/>
<xsl:variable name="vNumWords" select="count($vWords)"/>
<xsl:variable name="vLastWordPos" select=
"for $k in 1 to vNumWords
return
if(string-length(string-join($vWords[position() le $k],
' ')
)
le $pMaxLength
and
string-length(string-join($vWords[position() le $k+1],
' ')
)
gt $pMaxLength
)
then $k
else ()
"/>
<xsl:variable name="vLastPos" select=
"($vLastWordPos, $vNumWords)[1]"/>
<span>
<p>
<xsl:value-of select=
"string-join($vWords[position() lt $vLastPos], ' '),
string-join($vWords[position() ge $vLastPos], ' ')
"
separator="
"/>
</p>
</span>
</xsl:template>
</xsl:stylesheet>
应用于提供的 XML 文档时:
<ELEMENT attribute="Value of the attribute">Some text</ELEMENT>
产生了想要的正确结果:
<span>
<p>Value of the
attribute</p>
</span>
请注意:由于输出是 HTML,您可能希望在上面的代码中替换它:
<span>
<p>
<xsl:value-of select=
"string-join($vWords[position() lt $vLastPos], ' ')"/>
<br />
<xsl:value-of select=
"string-join($vWords[position() ge $vLastPos], ' ')"/>
</p>
</span>