Caleb Madrigal

Programming, Hacking, Math, and Art


Embedding an XSLT in an XML document

Today, I had this XML document which I was wanting to make viewable in a browser. My plan was to run the XML document through an XSLT engine to transform it into an HTML document (which could then be opened in a browser).

Instead, I found that I could just embed the XSLT directly in the XML document. Then, when this file is opened in a browser, the XSLT executes and spits out HTML, which is then rendered into the browser window. This is great because I now have the original XML file (which we wanted to keep further analysis purposes) which can also be rendered nicely in a browser.

Here's an example:

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xml" href="#stylesheet"?>
<!DOCTYPE catelog [
<!ATTLIST xsl:stylesheet
  id    ID  #REQUIRED>
<xsl:stylesheet id="stylesheet" version="1.0" xmlns:xsl="">
<xsl:template match="/">
  <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
      <xsl:for-each select="catalog/cd">
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="artist"/></td>

        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <company>CBS Records</company>

And this renders as such:

XSLT Render

Please note that this doesn't work for Internet Explorer. For IE, the XSL document must be referenced like this:

<?xml-stylesheet type="text/xml" href="report.xsl"?>