Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 20th, 2012  |  syntax: None  |  size: 1.89 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. XSLT applied to an external CSV file, How?
  2. <xsl:stylesheet version="2.0"
  3.     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  4.     xmlns:xs="http://www.w3.org/2001/XMLSchema"
  5.     xmlns:fn="fn"
  6.     exclude-result-prefixes="xs fn">
  7.  
  8. <xsl:output indent="yes" encoding="US-ASCII"/>
  9.  
  10. <xsl:param name="pathToCSV" select="'file:///C:/Downloads/inputcsv.csv'"/>
  11.  
  12. <xsl:function name="fn:getTokens" as="xs:string+">
  13.     <xsl:param name="str" as="xs:string"/>
  14.         <xsl:analyze-string select="concat($str, ',')" regex='(("[^"]*")+|[^,]*),'>
  15.             <xsl:matching-substring>
  16.                 <xsl:sequence select='replace(regex-group(1), "^""|""$|("")""", "$1")'/>
  17.             </xsl:matching-substring>
  18.         </xsl:analyze-string>
  19. </xsl:function>
  20.  
  21. <xsl:template match="/" name="main">
  22.     <xsl:choose>
  23.         <xsl:when test="unparsed-text-available($pathToCSV)">
  24.             <xsl:variable name="csv" select="unparsed-text($pathToCSV)"/>
  25.             <xsl:variable name="lines" select="tokenize($csv, '&#xD;')" as="xs:string+"/>
  26.             <xsl:variable name="elemNames" select="fn:getTokens($lines[1])" as="xs:string+"/>
  27.             <root>
  28.                 <xsl:for-each select="$lines[position() > 0]">
  29.                     <row>
  30.                         <xsl:variable name="lineItems" select="fn:getTokens(.)" as="xs:string+"/>
  31.  
  32.                         <xsl:for-each select="$elemNames">
  33.                             <xsl:variable name="pos" select="position()"/>
  34.                             <column>
  35.                                 <xsl:value-of select="$lineItems[$pos]"/>
  36.                             </column>
  37.                         </xsl:for-each>
  38.                     </row>
  39.                 </xsl:for-each>
  40.             </root>
  41.         </xsl:when>
  42.         <xsl:otherwise>
  43.             <xsl:text>Cannot locate : </xsl:text><xsl:value-of select="$pathToCSV"/>
  44.         </xsl:otherwise>
  45.     </xsl:choose>
  46. </xsl:template>
  47.  
  48. </xsl:stylesheet>