2

我想\L在 25 个字符后插入一个字符串(在本例中为换行符,),但只能在下一个可用空格处插入,以避免拆分如下所示的单词:

This is the example sente\L nce for you.

正确的输出应该是这样的:

This is the example sentence\L for you.

换行应该出现在每行大约 25 个字符之后,因此更长的示例如下所示:

This is a longer example\L
for you; it actually contains\L
more than 50 characters.

在 XQuery 中实现这一点的最简单方法是什么?

4

2 回答 2

2

这是一个 XSLT 2.0 解决方案——只需将其转换为 XQuery

<xsl:stylesheet version="2.0"   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:my="my:my" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:value-of select="my:splitAtWords(/*, 25, '\L&#xA;')"/>
 </xsl:template>

 <xsl:function name="my:splitAtWords" as="xs:string?">
  <xsl:param name="pText" as="xs:string?"/>
  <xsl:param name="pMaxLen" as="xs:integer"/>
  <xsl:param name="pRep" as="xs:string"/>

  <xsl:sequence select=
  "if($pText)
    then
     (for $line in replace($pText, concat('(^.{1,', $pMaxLen,'})\W.*'), '$1')
       return
          concat($line, $pRep,
                 my:splitAtWords(substring-after($pText,$line),$pMaxLen,$pRep))
      )
    else ()
  "/>
 </xsl:function>
</xsl:stylesheet>

当此转换应用于以下 XML 文档时:

<t>This is a longer example for you; it actually contains more than 50 characters.</t>

产生了想要的结果

This is a longer example\L
 for you; it actually\L
 contains more than 50\L
 characters\L
.\L
于 2012-09-10T13:40:43.803 回答
1

我最终使用了这里提出的解决方案:

let $text := 'This is a longer example for you; it actually contains more than 50 characters.'
let $text-output := replace(concat($text,' '),'(.{0,25}) ','$1\\L')
return $text-output

它返回的结果与上面 @dimitre-novatchev 的 XSLT 相同:

This is a longer example\L
for you; it actually\L
contains more than 50\L
characters.\L
于 2012-09-10T14:47:44.037 回答