Convert XML to Groovy

Having discovered that I couldn’t simply embed a bunch of XSL-FO templates into my Groovy classes as Strings, I’m looking for a way to convert XSL-FO to Groovy MarkupBuilder script.

There are lots of articles about how to use Groovy to write or consume XML. There are not so many about how to convert in the opposite direction. Codehaus.org gives a brief example in Creating XML using Groovy’s MarkupBuilder of how to use the DomToGroovy class.

Based on that example, I created a class with a method for converting XML to Groovy and a script to call it from the command line.

Unfortunately, DomToGroovy doesn’t seem to handle XSL-FO so well. Still this will be a handy tool to keep around.

ConvertXml.groovy:

package com.geekcredential.common.fileformat.xml
/**
* Based on http://groovy.codehaus.org/Creating+XML+using+Groovy's+MarkupBuilder
*/
import org.codehaus.groovy.tools.xml.DomToGroovy
import javax.xml.parsers.DocumentBuilderFactory
import org.apache.log4j.Logger

public class ConvertXml {

static Logger log = new Logger("com.geekcredential.common.fileformat.xml.ConvertXml")

static void toGroovy(String sourcePath, String targetPath) {
try {
File sourceFile = new File(sourcePath)
File targetFile = new File(targetPath)

def builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream = new ByteArrayInputStream(sourceFile.readBytes())
def document = builder.parse(inputStream)
def output = new StringWriter()
def converter = new DomToGroovy(new PrintWriter(output))

converter.print(document)
targetFile.withWriter {fw ->
fw << output.toString()
}
} catch (Throwable t) {
log.fatal("Error converting XML file to Groovy script", t)
}
}
}

xmlToGroovy.groovy:

import com.geekcredential.common.fileformat.xml.ConvertXml

def targetFilePath = new String()

if (args.size() 2) {
println "Usage: groovy xmlToGroovy.groovy sourceFilePath [targetFilePath]"
println "(If targetFilePath is not specified, output will be written to"
println "the same name as sourceFilePath, but with a .groovy extension.)"
System.exit(1)
}

def sourceFilePath = args[0]

if (args.size() == 1) {
targetFilePath = sourceFilePath.substring(0, sourceFilePath.lastIndexOf(".")) + ".groovy"
} else {
targetFilePath = args[1]
}

ConvertXml.toGroovy(sourceFilePath.toString(), targetFilePath.toString())

System.exit(0)

Advertisements

#domtogroovy, #groovy, #xml, #xsl-fo