hannah
hannah

Reputation: 41

Splitting of strings based on the required length

Is there an easy way on how to split a string based from the required length? For example, I have a string:

<Data>AAAAABBBBB1111122222RRRRR<Data>

and I want to populate an output like this:

AAAAA
BBBBB
11111
22222
RRRRR

Thank you.

Upvotes: 2

Views: 1046

Answers (2)

jmd
jmd

Reputation: 1051

You can use analyze-string only with xslt 2.0 which several processors don't handle (especially libxslt doesn't, so the default python bindings don't).
So analyze-string version will break with them, and not necessarily with a clear error message.

For xslt 1.0 compatibility, you can use instead a recursive template to do it :

<xsl:template match="mydatatosplit">
    <xsl:call-template name="split-string">
        <xsl:with-param name="string" select="."/>
    </xsl:call-template>
</xsl:template>

<xsl:template name="split-string">
    <xsl:param name="string"/>
    <xsl:param name="length" select="5"/>
    <xsl:value-of select="substring($string, 1, $length)"/>&#10;
    <xsl:if test="string-length($string) > $length">
        <!-- recursive call -->
        <xsl:call-template name="split-string">
            <xsl:with-param name="string" select="substring($string, $length + 1)"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

Upvotes: 0

Martin Honnen
Martin Honnen

Reputation: 167401

You can use analyze-string to break up the data:

<xsl:template match="Data">
    <xsl:variable name="tokens" as="xs:string*">
        <xsl:analyze-string select="." regex=".{{1,5}}">
            <xsl:matching-substring>
                <xsl:sequence select="."/>
            </xsl:matching-substring>
        </xsl:analyze-string>
    </xsl:variable>
    <xsl:value-of select="$tokens" separator="&#10;"/>
</xsl:template>

Upvotes: 4

Related Questions