Transform XML with XSLT using Java

7 Flares Twitter 0 Facebook 0 Google+ 7 Pin It Share 0 LinkedIn 0 7 Flares ×

XML and XSLT makes data exchange and rendering of the data in various formats easier. XML is pretty good for portable data exchanges, well structured data formats and helps in open standards. XSLT on the other hand can transform the XML to other formats. For example transforming the XML to HTML so that it can be rendered in browser. Let us explore how we can transform an XML using XSLT in Java language. Think of XSLT as a scripting language for transforming XML.

XML – students.xml

 XSLT – students.xslt

The XML and the XSLT is ready.  The XSLT is very simple. It presents the data in tabular format with the help of HTML. Using the for-each construct of xsl, we iterate over the student element and put each student as a row. The part left is how to apply this XSL on the given XML and generate the HTML content using a Java program. This is what we will be doing in the next section.


Java Program

Classes in the package javax.xml.transform.* will help us in transforming the XML using XSL.

  • The transformer class is initialized with the xsl file ( args[1])
  • The transformer’s transform method is invoked supplying it the xml input ( args[0]) and the name of the output file ( args[2])

You can run the program using

$  java XSLTransformer students.xml students.xsl students.html




You can also try generating other output formats using the xsl.