我想将一个长句子分成多行,同时在句子末尾保留完整的单词。我的行长为 40,所以它应该打印当前单词,如果行长超过 40,则它会继续到下一行。所有的分隔符都是空格,我目前没有将单词作为标记检索。这似乎非常困难,因为我仅限于使用 XSLT 1.0。
示例来自:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut mi neque, sit amet tincidunt magna. Phasellus eleifend suscipit neque, at pretium enim facilisis non. Aenean a ornare eros.
所需示例:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Aenean ut mi neque, sit
amet tincidunt magna. Phasellus eleifend
suscipit neque, at pretium enim facilisis
non. Aenean a ornare eros.
目前我正在使用现有的 XSL 方法:
<xsl:template name="nextline">
<xsl:param name="return"/>
<xsl:param name="width"/>
<xsl:choose>
<!-- when the string-length is greater than the width -->
<xsl:when test="(string-length($return) div string-length($width)) > 1">
<xsl:value-of select="concat(substring($return,1,$width - 1), ' ')"/>
<xsl:call-template name="nextline">
<xsl:with-param name="return" select="substring($return, $width)"/>
<xsl:with-param name="width" select="$width"/>
</xsl:call-template>
</xsl:when>
<!-- just print the string length -->
<xsl:otherwise>
<xsl:value-of select="substring($return,1,$width - 1)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
当前的,不需要的,例如:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Aenean ut mi neque, s
it amet tincidunt magna. Phasellus elei
fend suscipit neque, at pretium enim fa
cilisis non. Aenean a ornare eros.
下面的部分解决方案导致:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Aenean ut mi neque, sit
amet tincidunt magna. Phasellus eleifend
suscipit neque, at pretium enim facilisis
non. Aenean a ornare eros.
最佳答案
我很想为此目的使用扩展函数,而不是尝试使用纯 XSLT 对其进行编码。您在问题中说您正在使用 javax.xml.transform,它默认使用支持 Java 扩展功能的 Xalan。 Apache commons-lang 3.1提供静态方法WordUtils.wrap这似乎完全符合您的需要,如果您将该库添加到您的项目中,那么您可以将其作为扩展名调用,如下所示
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:wu="xalan://org.apache.commons.lang3.text.WordUtils"
exclude-result-prefixes="wu">
<xsl:template match=".....">
<xsl:value-of select="wu:wrap(stringToWrap, 40)" />
</xsl:template>
</xsl:stylesheet>
如果您要从元素中获取要换行的值,您可能需要使用 string 函数,即 wu:wrap(string(someElement), 40)
关于xml - XSLT 1.0 : How can I format a paragraph over multiple lines whilst keeping a token intact?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143864/