2
<xsl:variable name="string" select="'abcdefghijklmnopqrstuvwxyz'" />

I would need to convert this string to a node, grouped by 5 characters, obviously the last group can be less than or equal to 5 characters depending on the input string

<node>
  <a>abcde</a>
  <a>fghij</a>
  <a>klmno</a>
  <a>pqrst</a>
  <a>uvwxy</a>
  <a>z</a>
</node>

2 Answers 2

3

This transformation:

<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="pStr" select="'abcdefghijklmnopqrstuvwxyz'" />
 <xsl:param name="pChunkSize" select="5"/>

 <xsl:template match="/*">
  <node>
    <xsl:call-template name="split"/>
  </node>
 </xsl:template>

 <xsl:template name="split">
  <xsl:param name="pStr" select="$pStr" />
  <xsl:param name="pChunkSize" select="$pChunkSize"/>

  <xsl:variable name="pRemLength" select="string-length($pStr)"/>

  <xsl:if test="$pRemLength">
   <a><xsl:value-of select="substring($pStr, 1, $pChunkSize)"/></a>

   <xsl:call-template name="split">
    <xsl:with-param name="pStr" select="substring($pStr, $pChunkSize+1)"/>
    <xsl:with-param name="pChunkSize" select="$pChunkSize"/>
   </xsl:call-template>
  </xsl:if>

 </xsl:template>
</xsl:stylesheet>

when applied on any XML document (not used), produces the wanted, correct result:

<node>
   <a>abcde</a>
   <a>fghij</a>
   <a>klmno</a>
   <a>pqrst</a>
   <a>uvwxy</a>
   <a>z</a>
</node>

Explanation: Primitive recursion with no string length as the stop condition, and with each recursion step producing the next chunk and cutting it from the string.

Sign up to request clarification or add additional context in comments.

Comments

1

here is a similar question with an answer which you can change it easily to cover your question: http://www.jguru.com/faq/view.jsp?EID=1070072

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.