使用XSLT的块字符串

时间:2011-10-14 13:57:26

标签: string xslt xslt-2.0 chunks

我有一个带有文本节点的XML,我需要使用XSLT 2.0将此字符串拆分为多个块。例如:

<tag>
    <text>This is a long string 1This is a long string 2This is a long string 3This is a long string 4</text>
</tag>

输出应为:

<tag>
    <text>This is a long string 1</text>
    <text>This is a long string 2</text>
    <text>This is a long string 3</text>
    <text>This is a long string 4</text>
</tag>

请注意,我故意将块大小设置为每个语句的长度,以便示例更容易读取和写入,但转换应该接受任何值(可以对此值进行硬编码)。

1 个答案:

答案 0 :(得分:1)

此XSLT 1.0转换

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

 <xsl:param name="pChunkSize" select="23"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="text/text()" name="chunk">
  <xsl:param name="pText" select="."/>

  <xsl:if test="string-length($pText) >0">
   <text><xsl:value-of select=
   "substring($pText, 1, $pChunkSize)"/>
   </text>
   <xsl:call-template name="chunk">
    <xsl:with-param name="pText"
    select="substring($pText, $pChunkSize+1)"/>
   </xsl:call-template>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<tag>
    <text>This is a long string 1This is a long string 2This is a long string 3This is a long string 4</text>
</tag>

生成想要的正确结果

<tag>
    <text>
        <text>This is a long string 1</text>
        <text>This is a long string 2</text>
        <text>This is a long string 3</text>
        <text>This is a long string 4</text>
        <text/>
    </text>
</tag>

<强> II。 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="pChunkSize" select="23"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="text/text()">
  <xsl:variable name="vtheText" select="."/>
  <xsl:for-each select=
      "0 to string-length() idiv $pChunkSize">
   <text>
    <xsl:sequence select=
     "substring($vtheText, . *$pChunkSize +1, $pChunkSize) "/>
   </text>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>