The Hello World Java Program

Our last two transformations don’t involve XML vocabularies at all; they use XSLT to convert the Hello World document into other formats. Next, we’ll transform our XML source document into the source code for a Java program. When the program is compiled and executed, it prints the message from the XML document to the console. Here’s our stylesheet:

<?xml version="1.0"?>
<!-- java-greeting.xsl -->
<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text" encoding="UTF-8"/>

  <xsl:template match="/">
    <xsl:text>
public class Greeting
{
  public static void main(String[] argv)
  {
    </xsl:text>
    <xsl:apply-templates select="greeting"/>
    <xsl:text>
  }
}
    </xsl:text>
  </xsl:template>

  <xsl:template match="greeting">
    <xsl:text>System.out.println("</xsl:text>
    <xsl:value-of select="normalize-space()"/>
    <xsl:text>");</xsl:text>
  </xsl:template>

</xsl:stylesheet>

(Notice that we used <xsl:output method="text"> to generate text, not markup.) Our stylesheet produces these results:

public class Greeting
{
  public static void main(String[] argv)
  {
    System.out.println("Hello, World!");
  }
}

The class name defined in the XSLT stylesheet (Greeting) must be the name of the generated file. That means we have to specify the case-sensitive filename when we run the transformation. Here’s how to do that with Xalan:

java org.apache.xalan.xslt.Process -in greeting.xml -xsl java-greeting.xsl 
    -out Greeting.java

For Saxon, the syntax is slightly simpler: ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.