Reputation: 153
trying to convert an XML file of the following sort to a flat file or csv. I am able to generate XSLT files for other XML formats, but I don't really understand how to work with trees structure in this format. Any thoughts? I've experimented a bit, but I'm just not familiar with XSLT enough.
<observations
realtime_start="2013-02-08"
realtime_end="2013-02-08"
observation_start="1776-07-04"
observation_end="9999-12-31" units="lin"
output_type="2"
file_type="xml"
order_by="observation_date"
sort_order="asc"
count="792" offset="0"
limit="100000">
<observation date="1947-01-01" CPIAUCSL_20130208="21.48"/>
<observation date="1947-02-01" CPIAUCSL_20130208="21.62"/>
<observation date="1947-03-01" CPIAUCSL_20130208="22.0"/>
</observations>
Upvotes: 1
Views: 7054
Reputation: 4393
Will this example suffice?
T:\ftemp>type obs.xml
<?xml version="1.0" encoding="UTF-8"?>
<observations realtime_start="2013-02-08" realtime_end="2013-02-08"
observation_start="1776-07-04" observation_end="9999-12-31" units="lin"
output_type="2" file_type="xml" order_by="observation_date" sort_order="asc"
count="792" offset="0" limit="100000">
<observation date="1947-01-01" CPIAUCSL_20130208="21.48"/>
<observation date="1947-02-01" CPIAUCSL_20130208="21.62"/>
<observation date="1947-03-01" CPIAUCSL_20130208="22.0"/>
</observations>
T:\ftemp>xslt obs.xml obs.xsl obs.csv
T:\ftemp>type obs.csv
date,CPIAUCSL
1947-01-01,21.48
1947-02-01,21.62
1947-03-01,22.0
T:\ftemp>type obs.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="text"/>
<xsl:template match="observations">
<xsl:text>date,CPIAUCSL
</xsl:text>
<xsl:for-each select="observation">
<xsl:value-of select="@date"/>,<xsl:value-of select="@CPIAUCSL_20130208"/>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
T:\ftemp>
The key to outputting text is that what gets serialized to the file are all of the text nodes of the result tree. Any element or attribute nodes in the result tree are ignored, so don't even bother trying to create them ... just create text nodes and they all get concatenated into the output.
To go in the other direction, from CSV to XML, I've made the http://www.CraneSoftwrights.com/resources/#csv package freely available (and it works for TSV files as well) for use with XSLT 2.0.
Upvotes: 4