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.javaFor Saxon, the syntax is slightly simpler: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access