Created
May 8, 2017 15:46
-
-
Save Phu2/e5f01072e4bb37f5c1762bae732e6c73 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0"?> | |
<!-- | |
Based on http://andrewjwelch.com/code/xslt/csv/csv-to-xml_v2.html | |
2017-05-06, phu@openbiblio.eu | |
--> | |
<xsl:stylesheet version="2.0" | |
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" | |
xmlns:xs="http://www.w3.org/2001/XMLSchema" | |
xmlns:fn="fn" | |
exclude-result-prefixes="xs fn"> | |
<xsl:output indent="yes" encoding="UTF-8"/> | |
<xsl:param name="pathToCSV" select="'test.csv'"/> | |
<xsl:function name="fn:getTokens" as="xs:string+"> | |
<xsl:param name="str" as="xs:string"/> | |
<xsl:analyze-string select="concat($str, ',')" regex='(("[^"]*")+|[^,]*),'> | |
<xsl:matching-substring> | |
<xsl:sequence select='replace(regex-group(1), "^""|""$|("")""", "$1")'/> | |
</xsl:matching-substring> | |
</xsl:analyze-string> | |
</xsl:function> | |
<xsl:template name="main"> | |
<xsl:choose> | |
<xsl:when test="unparsed-text-available($pathToCSV)"> | |
<xsl:variable name="csv" select="unparsed-text($pathToCSV)"/> | |
<!--Split lines by Unix and Windows line endings, see https://www.w3.org/TR/xslt20/#d5e22242--> | |
<xsl:variable name="lines" select="tokenize($csv, '\r?\n')" as="xs:string+"/> | |
<root> | |
<xsl:for-each select="$lines[position() > 1]"> | |
<xsl:variable name="lineItems" select="fn:getTokens(.)" as="xs:string+" /> | |
<line id="{$lineItems[1]}" collection="{$lineItems[2]}" title="{$lineItems[3]}" parent="{$lineItems[4]}"/> | |
</xsl:for-each> | |
</root> | |
</xsl:when> | |
<xsl:otherwise> | |
<xsl:text>Cannot locate : </xsl:text><xsl:value-of select="$pathToCSV"/> | |
</xsl:otherwise> | |
</xsl:choose> | |
</xsl:template> | |
</xsl:stylesheet> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment