Vinay Gaba
Vinay Gaba

Reputation: 1214

How to parse a delimited string?

I have a delimited string of the following format :

1^^2^^3^^4^^5^^||1^^2^^3^^4^^5^^||

where ^^ is the column delimiters and || is the row delimiter. I need to be able to iterate through each row and then each column and store the values in different variables. I was wondering how it could be done using XSL 1.0. Any sort of help would be really appreciated

Upvotes: 0

Views: 117

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167401

Here is an example using the template based implementation of EXSLT's str:split:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:exsl="http://exslt.org/common"
  xmlns:str="http://exslt.org/strings"
  exclude-result-prefixes="exsl str">

<xsl:import href="http://exslt.org/str/functions/split/str.split.template.xsl"/>

<xsl:output indent="yes"/>

<xsl:template match="data">
  <xsl:variable name="rows-rtf">
    <xsl:call-template name="str:split">
      <xsl:with-param name="string" select="."/>
      <xsl:with-param name="pattern" select="'||'"/>
    </xsl:call-template>
  </xsl:variable>
  <xsl:variable name="rows" select="exsl:node-set($rows-rtf)/token[normalize-space()]"/>
  <xsl:for-each select="$rows">
    <row>
      <xsl:variable name="cols-rtf">
        <xsl:call-template name="str:split">
          <xsl:with-param name="string" select="."/>
          <xsl:with-param name="pattern" select="'^^'"/>
        </xsl:call-template>
      </xsl:variable>
      <xsl:variable name="cols" select="exsl:node-set($cols-rtf)/token[normalize-space()]"/>
      <xsl:for-each select="$cols">
        <col><xsl:value-of select="."/></col>
      </xsl:for-each>
    </row>
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Outputs

<row>
   <col>1</col>
   <col>2</col>
   <col>3</col>
   <col>4</col>
   <col>5</col>
</row>
<row>
   <col>1</col>
   <col>2</col>
   <col>3</col>
   <col>4</col>
   <col>5</col>
</row>
<row>
   <col>a</col>
   <col>b</col>
   <col>c</col>
   <col>d</col>
   <col>c</col>
</row>

for the input sample

<root>
  <data>1^^2^^3^^4^^5^^||1^^2^^3^^4^^5^^||a^^b^^c^^d^^c</data>
</root>

Upvotes: 3

Related Questions