'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.
Solution 1:[1]
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=" "/>
</xsl:template>
Solution 2:[2]
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)"/>
<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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel Haley |
| Solution 2 |
