Skip to content

Instantly share code, notes, and snippets.

@bzerangue
Last active October 16, 2020 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bzerangue/788f4429c61135f5e861c9ab095e0193 to your computer and use it in GitHub Desktop.
Save bzerangue/788f4429c61135f5e861c9ab095e0193 to your computer and use it in GitHub Desktop.
Testing XML to CSV (via XSLT), https://data.ny.gov/api/views/k7gz-mn77/rows.xml
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:variable name="delimiter" select="','" />
<!-- define an array containing the fields we are interested in -->
<xsl:variable name="fieldArray">
<field>date</field>
<field>ny_conventional_gasoline_spot_price_gal</field>
<field>ny_ultra_low_sulfur_diesel_spot_price_gal</field>
<field>wti_crude_oil_spot_price_barrel</field>
<field>brent_crude_oil_spot_price_barrel</field>
</xsl:variable>
<xsl:param name="fields" select="document('')/*/xsl:variable[@name='fieldArray']/*" />
<xsl:template match="/">
<!-- output the header row -->
<xsl:for-each select="$fields">
<xsl:if test="position() != 1">
<xsl:value-of select="$delimiter"/>
</xsl:if>
<xsl:value-of select="." />
</xsl:for-each>
<!-- output newline -->
<xsl:text>&#xa;</xsl:text>
<xsl:apply-templates select="response/row/row"/>
</xsl:template>
<xsl:template match="row/row">
<xsl:variable name="currNode" select="." />
<!-- output the data row -->
<!-- loop over the field names and find the value of each one in the xml -->
<!-- output the data row -->
<!-- loop over the field names and find the value of each one in the xml -->
<xsl:for-each select="$fields">
<xsl:if test="position() != 1">
<xsl:value-of select="$delimiter"/>
</xsl:if>
<xsl:text>"</xsl:text>
<xsl:value-of select="$currNode/*[name() = current()]" />
<xsl:text>"</xsl:text>
</xsl:for-each>
<!-- output newline -->
<xsl:text>&#xa;</xsl:text>
</xsl:template>
</xsl:stylesheet>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment