Jump to content
Alex_2

How to split a string into an array using xpath

Recommended Posts

I'm trying to break a string into an array based on the length. for Ex: If I have a string of 30 characters, I want to convert into an array of 5 characters each using an xpath function.


Is there any way to do this? Also, I noticed in this thread - Creating an incremental count variable in XSLT / XPath when using Xpath for..in..return?


that we can use "For" as "For $i in 1 to $length return $i". When I'm trying to use "1 to 5" i.e. constants, xpath is accepting, but when I'm trying to pass a variable " 1 to $length", xpath is not accepting.


Please suggest ASAP.


Alex


Share this post


Link to post
Share on other sites

Which XSLT processor do you use, which XSLT version? There are no arrays in XSLT 1.0 and 2.0, so your whole question about "splitting into an array" sounds odd. Unless you work with XPath 3.1 where arrays exist but then you need to tell so.

Share this post


Link to post
Share on other sites

Assuming you have an XSLT 2.0 processor like Saxon 9 or XmlPrime or Exselt or Altova and you want to split up a string into a sequence of strings where each string has a certain size then

 

[

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:xs="http://www.w3.org/2001/XMLSchema"
	xmlns:mf="http://example.com/mf"
	exclude-result-prefixes="xs mf"
	version="2.0">
	
	<xsl:function name="mf:split" as="xs:string*">
		<xsl:param name="input" as="xs:string"/>
		<xsl:param name="size" as="xs:integer"/>
		<xsl:for-each-group select="string-to-codepoints($input)" group-adjacent="(position() - 1) idiv $size">
			<xsl:sequence select="codepoints-to-string(current-group())"/>
		</xsl:for-each-group>
	</xsl:function>
	
	<xsl:template match="/" name="main">
		<xsl:value-of select="mf:split('123456789012345678901234567890123', 5)" separator="
"/>
	</xsl:template>
</xsl:stylesheet>

outputs

12345
67890
12345
67890
12345
67890
123

Share this post


Link to post
Share on other sites

Hi,

 

 

This must be XSLT 1.0 or 2.0, definitely not 3 but I'm able to use the function "For $i in 1 to 5 return $i" and not "For $i in 1 to $length return $i".

What could be the issue?

 

 

Alex

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×