Converting an XML to an HTML using XSLT with Xalan

Xalan is an Apache implementation of the W3C recommendations for XSL transformations, XSLT. XSLT allows you to transform xml documents in an HTML, another XML or whatever format you desire.

Download Xalan at http://xml.apache.org/xalan-j/index.html.

You can apply an XSL to an XML document with command line. Make sure xalan.xml is in your classpath before trying out this example. It will create an HTML file (check it out!) from an XML.

  
  java org.apache.xalan.xslt.Process -in customers.xml -xsl customers.xsl -out customers.html

customers.xml (!!remove the space between ? and xml):

<? xml version="1.0"?>
<!DOCTYPE customers SYSTEM "customers.dtd">
 
<customers>
   <customer id="cust1">
      <name>Joris Van den Bogaert</name>
      <address>
         <addressline1>Handelskaai 3</addressline1>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BE</country>
      </address>
      <address>
         <addressline1>A. Dewitstraat 50</addressline1>
         <zip>3078</zip>
         <location>Meerbeek</location>
         <country>BE</country>
      </address>
   </customer>
  
   <customer id="cust2">
      <name>Alicia Kolesnikova</name>
      <address>
         <addressline1>Handelskaai 3</addressline1>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BE</country>
      </address>
   </customer>
</customers>

customers.dtd:

<!ELEMENT customers (customer*)>
<!ELEMENT customer (name, address+)>
<!ELEMENT address (addressline1, addressline2, zip, location, country)>
 
<!ELEMENT name (#PCDATA)>
 
<!ELEMENT addressline1 (#PCDATA)>
<!ELEMENT addressline2 (#PCDATA)>
<!ELEMENT zip (#PCDATA)>
<!ELEMENT location (#PCDATA)>
<!ELEMENT country (#PCDATA)>
 
<!ATTLIST customer
   id NMTOKEN #REQUIRED
>

customers.xsl (!!remove the space between ? and xml):

<? xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 
<xsl:template match="customers">
<html>
   <head><title>Customers</title></head>
   <body>
      <h1>Customers</h1>
      <table border="1">
         <th>Customer ID</th>
         <th>Name</th>
         <th>Addresses</th>
     
         <xsl:apply-templates/>
 
      </table>
   </body>
</html>
</xsl:template>
 
<xsl:template match="customer">
   <tr>
      <td><xsl:value-of select="@id"/></td>
      <td><xsl:value-of select="name"/></td>
 
      <td><xsl:apply-templates select="address"/></td>
   </tr>
</xsl:template>
 
<xsl:template match="address">
   <xsl:value-of select="addressline1"/>
   <xsl:if test="string(addressline2) != string('')">
      &#160;<xsl:value-of select="addressline2"/>
   </xsl:if>,
   <xsl:value-of select="zip"/>&#160;<xsl:value-of select="location"/> 
   [<xsl:value-of select="country"/>]<br/>
</xsl:template>
 
</xsl:stylesheet>