Generating an HTML file from an XSL Style Sheet and an XML using Java.

For future reference..

I have this xml file called source.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
    </cd>
</catalog>

And this xsl file, style.xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <h2>My CD Collection</h2>
                <table border="1">
                    <tr bgcolor="#9acd32">
                        <th style="text-align:left">Title</th>
                        <th style="text-align:left">Artist</th>
                    </tr>
                    <xsl:for-each select="catalog/cd">
                        <tr>
                            <td>
                                <xsl:value-of select="title"/>
                            </td>
                            <td>
                                <xsl:value-of select="artist"/>
                            </td>
                        </tr>
                    </xsl:for-each>
                </table>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

And of course the source code:
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
 
public class TestClass {
 
    public static void main(String[] args) throws Exception {
        final StreamSource style = new StreamSource("style.xsl");
        final StreamSource data = new StreamSource("source.xml");
 
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer(style);
 
        final StreamResult outputTarget = new StreamResult(new FileOutputStream("result.html"));
 
        transformer.transform(data, outputTarget);
    }
 
}

Now, put these 3 files in the same folder, and simply compile, execute, validate...
Korays-MacBook-Pro:~ koraytugay$ javac TestClass.java
Korays-MacBook-Pro:~ koraytugay$ java TestClass

And then open result.html in your browser and see the magic: