带 XSLT 的块字符串 [英] Chunk string with XSLT

查看:30
本文介绍了带 XSLT 的块字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an XML with a text node, and I need to split this string into multiple chunks using XSLT 2.0. For example:

<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>

请注意,我特意将块大小设置为每个语句的长度,以便示例更易于阅读和编写,但转换应接受任何值(此值可以硬编码).

Note that I deliberately set the chunk size to the length of each statement so that the example is easier to read and write, but the transformation should accept any value (it is okay for this value to be hardcoded).

推荐答案

这个 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>

二.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>

这篇关于带 XSLT 的块字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆