Archive for March 20th, 2010

20
Mar
10

Java Command Line XSLT Transformation

This page describes the process of transforming XML using Java via the command line.

Not too long ago Java integrated the XSLTC compiler that allowed developers to compile their stylesheets into class files. These class files can be run to perform transformations on xml input.

Transformation using Command Line

As of JDK 1.5 you can run the following commands to do a translation.

The first step is to compile the style sheet into a .class file.

java com.sun.org.apache.xalan.internal.xsltc.cmdline.Compile [-o <output>]
      [-d <directory>] [-j <jarfile>] [-p <package>]
      [-n] [-x] [-u] [-v] [-h] { <stylesheet> | -i }

Next we use the compiled transformation to convert a document over.

java com.sun.org.apache.xalan.internal.xsltc.cmdline.Transform
     [-j <jarfile>] [-x] {-u <document_url> | <document>} <class>
     [<name1>=<value1> 

XML document

In the following example we define an xml source.

src/main/resources/com/test/test.xml

<?xml version="1.0"?>
<hello-world>
   <greeter>An XSLT Programmer</greeter>
   <greeting>Hello, World!</greeting>
</hello-world>

Stylesheet

src/main/resources/com/test/test.xsl

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/hello-world">
    <HTML>
      <HEAD>
        <TITLE></TITLE>
      </HEAD>
      <BODY>
        <H1>
          <xsl:value-of select="greeting"/>
        </H1>
        <xsl:apply-templates select="greeter"/>
      </BODY>
    </HTML>
  </xsl:template>
  <xsl:template match="greeter">
    <DIV>from <I><xsl:value-of select="."/></I></DIV>
  </xsl:template>
</xsl:stylesheet>

Compile and Transform

java com.sun.org.apache.xalan.internal.xsltc.cmdline.Compile test.xsl

At this point you should have test.class in your current directory.

java com.sun.org.apache.xalan.internal.xsltc.cmdline.Transform test.xml test

At this point you should see some results being printed out to the screen.




Follow

Get every new post delivered to your Inbox.

Join 50 other followers