Re: [xsl] XPath 2.0: string to sequence of characters

Subject: Re: [xsl] XPath 2.0: string to sequence of characters
From: "James A. Robinson" <jim.robinson@xxxxxxxxxxxx>
Date: Fri, 02 Feb 2007 08:28:18 -0800
> With XPath 2.0, what is the easiest way to split a string into a 
> sequence of strings of length one e.g.
>    "Kibology" into ("K", "i", "b", "o", "l", "o", "g", "y")
> I came up with e.g.
>     for $index in 1 to string-length("Kibology")
>     return substring("Kibology", $index, 1)
> but wonder whether there is a shorter/easier way.

You say XPath 2.0, so I'm not sure if you really mean only available
in XPath.  If you are really doing this in XSLT 2.0 you can always
write your own function, which you can then use within the XPath
selections:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"; version="2.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema";
  xmlns:f="uri:local-functions">
  
  <xsl:output method="text"/>
  
  <xsl:template name="example">
    <xsl:for-each select="f:split('howdy!')">
      <xsl:value-of select="concat('&quot;',.,'&quot;','&#10;')"/>
    </xsl:for-each>
  </xsl:template>
  
  <xsl:function name="f:split">
    <xsl:param name="str" as="xs:string"/>
    <xsl:analyze-string select="$str" regex=".">
      <xsl:matching-substring>
        <xsl:sequence select="."/>
      </xsl:matching-substring>
    </xsl:analyze-string>
  </xsl:function>

</xsl:stylesheet>

When run, returns:

$ saxon -it example split.xsl 
"h"
"o"
"w"
"d"
"y"
"!"

Jim

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
James A. Robinson                       jim.robinson@xxxxxxxxxxxx
Stanford University HighWire Press      http://highwire.stanford.edu/
+1 650 7237294 (Work)                   +1 650 7259335 (Fax)

Current Thread