Using Groovy to do xslt transformation

Following demo code shows how we can use Groovy and xslt templates to do a simple file transform.

To transform a file, we need to do following before we can get the final result:

  1. Get a source file, here we use a simple xml as a source
  2. Define a .xls file – xslt transformation file
  3. Use Groovy to link the process and create output

Following is the code of the Groovy script that calls:

import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource

// Load xslt
def xslt = new File("c:/test/product2.xsl").getText()

// create transformer
def transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader(xslt)))

// Load xml
def xml = new File("c:/test/product.xml").getText()

// Set output file
def output = new FileOutputStream("c:/test/product_output.xml")

// perform transformation
transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(output))

Following is the .xsl file defined:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
   version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
	<xsl:template match="/">
		<xsl:for-each select="//products/product[not(.=preceding::*)]">
	<li>
				<xsl:value-of select="."/></li>
</xsl:for-each>
	</xsl:template>
</xsl:stylesheet>

Following is the source .xml file:


<items>
  <item>
    <products>
      <product>laptop</product>
      <product>charger</product>
    </products>
  </item>
  <item>
    <products>
      <product>laptop</product>
      <product>headphones</product>
    </products>
  </item>
</items>

After running the groovy code, you got the result as following – not a correct format xml, but it’s what the transformation file requested:

<ul>
	<li>laptop</li>
	<li>charger</li>
	<li>headphones</li>
</ul>