I had some XML files containing structured data. I wanted to insert this data in to a SQL database. So I needed to figure out how to transform the XML into SQL statements. Turns out, there is something called XLST that can be used to programmatically transform XML files into... well... whatever you want. So here's how I used XSLT to transform XML into SQL statements.
- Download Saxon-HE from here: https://saxonica.com/download/java.xml
- Create your xml file:
<!-- /Users/sherwood/Code/cdcatalog.xsl -->
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Dark Side of the Moon</title>
<artist>Pink Floyd</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1973</year>
</cd>
</catalog>
- Create your xsl schema:
<!-- /Users/sherwood/Code/cdcatalog.xsl -->
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:for-each select="catalog/cd">
INSERT INTO cds (title, artist) VALUES (<xsl:value-of select="title"/>, <xsl:value-of select="artist"/>)
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
- Run Saxon to transform the xml file:
java -jar /Users/sherwood/Downloads/SaxonHE10-5J/saxon-he-10.5.jar -s:/Users/sherwood/Code/cdcatalog.xml -xsl:/Users/sherwood/Code/cdcatalog.xsl -o:/Users/sherwood/Code/output
You should now have a transformed file!