xsl-list
[Top] [All Lists]

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

2007-02-02 09:28:39
 
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(_dot_)robinson(_at_)stanford(_dot_)edu
Stanford University HighWire Press      http://highwire.stanford.edu/
+1 650 7237294 (Work)                   +1 650 7259335 (Fax)

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--