Skip to content

Instantly share code, notes, and snippets.

@pdaengeli
Last active June 8, 2017 17:11
Show Gist options
  • Save pdaengeli/7c23abace405a0f17818671cbecab351 to your computer and use it in GitHub Desktop.
Save pdaengeli/7c23abace405a0f17818671cbecab351 to your computer and use it in GitHub Desktop.
Transpose csv style data using XSLT
A1¦A2¦A3¦A4¦A5
B1¦B2¦B3¦B4¦B5
C1¦C2¦C3¦C4¦C5
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<!-- input file, to be stored in the same directory -->
<xsl:variable name="input" select="unparsed-text('input.txt')"/>
<!-- output file -->
<xsl:variable name="output" select="'output.txt'"/>
<!-- input separator, between fields ("Felder") -->
<xsl:variable name="inputSeparatorInternal" select="'¦'"/>
<!-- input separator, between arrays ("Verbundausprägungen") -->
<xsl:variable name="inputSeparatorExternal" select="'\n\r?'"/>
<!-- output separator, between values in fields ("Feldausprägungen") -->
<xsl:variable name="outputSeparatorInternal" select="'|'"/>
<!-- output separator, between fields ("Felder") -->
<xsl:variable name="outputSeparatorExternal" select="'‖'"/>
<!-- program logic below
===========================-->
<!-- this variable holds the number of fields ("Felder pro Verbund") -->
<xsl:variable name="valueCount">
<xsl:for-each select="tokenize($input,'\n\r?')[1]">
<xsl:value-of select="count(tokenize(.,$inputSeparatorInternal))"/>
</xsl:for-each>
</xsl:variable>
<!-- this variable holds the number of occurrences ("Verbundausprägungen") -->
<xsl:variable name="arrayCount">
<xsl:value-of select="count(tokenize($input,$inputSeparatorExternal))"/>
</xsl:variable>
<xsl:template match="/">
<xsl:result-document encoding="utf-8" omit-xml-declaration="true" href="{$output}">
<xsl:for-each select="1 to $valueCount">
<xsl:variable name="currentValueCount" select="."/>
<xsl:for-each select="1 to $arrayCount">
<xsl:value-of select="tokenize(tokenize($input,$inputSeparatorExternal)[current()],$inputSeparatorInternal)[$currentValueCount]"/>
<xsl:if test="current() lt number($arrayCount)">
<xsl:copy-of select="$outputSeparatorInternal"/>
</xsl:if>
</xsl:for-each>
<xsl:copy-of select="$outputSeparatorExternal"/>
</xsl:for-each>
</xsl:result-document>
</xsl:template>
</xsl:stylesheet>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment