This XPath 2.0 expression:
string-join(for $line in tokenize(line,'
'),
$length in string-length($line)
return if ($length > $pMaxLength)
then substring(replace($line,
concat('(.{1,',
$pMaxLength,
'})'),
'$1
'),
1,
$length + ceiling($length div $pMaxLength) -1)
else $line,
'
')
For test, this input:
<line>
line1
line2 line2 line2 line2
line3line3
line4line4
line5line5line5line5line5
</line>
With this XSLT 2.0 stylesheet:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:param name="pMaxLength" select="10"/>
<xsl:template match="/">
<xsl:value-of
select="string-join(
for $line in tokenize(line,'
'),
$length in string-length($line)
return if ($length > $pMaxLength)
then substring(replace($line,
concat('(.{1,',
$pMaxLength,
'})'),
'$1
'),
1,
$length +
ceiling($length div $pMaxLength) - 1)
else $line,
'
')"/>
</xsl:template>
</xsl:stylesheet>
Output:
line1
line2 line
2 line2 li
ne2
line3line3
line4line4
line5line5
line5line5
line5
Just in case, this XSLT 1.0 stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="line/text()" name="lines">
<xsl:param name="pString" select="."/>
<xsl:param name="pMaxLength" select="10"/>
<xsl:choose>
<xsl:when test="contains($pString,'
')">
<xsl:call-template name="lines">
<xsl:with-param name="pString"
select="substring-before($pString,'
')"/>
<xsl:with-param name="pMaxLength"
select="$pMaxLength"/>
</xsl:call-template>
<xsl:call-template name="lines">
<xsl:with-param name="pString"
select="substring-after($pString,'
')"/>
<xsl:with-param name="pMaxLength"
select="$pMaxLength"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat(substring($pString,1,$pMaxLength),
'
')"/>
<xsl:apply-templates
select="current()[string-length($pString) > $pMaxLength]">
<xsl:with-param name="pString"
select="substring($pString,$pMaxLength+1)"/>
<xsl:with-param name="pMaxLength" select="$pMaxLength"/>
</xsl:apply-templates>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>