XML from Java Properties in Groovy

XML from Java Properties in Groovy
This is something that I have found usefull over and over again – the ability to generate XML from a parameterised template and a standard Java properties file using Groovy. It can be run during the build phase in Maven to generate test XML on the fly based on the appliciations property configuration.

The first time I used this was for a custom Maven plugin that I wrote to generate Streambase builds but have used it to generate XML for unit tests numerous times since.


import groovy.text.XmlTemplateEngine
import java.util.Properties
import java.io.File
import java.io.FileWriter

//Takes a java props file, an XML template file and creates the given output file
void createFile(propertiesFile, templateFileName, outputFileName) {
	// read properties file given
	def props = new Properties()
	props.load(new FileInputStream(new File(propertiesFile)))
	// map to the bindings
	def bindings = [:]

	// create the template and make the output file
	def engine = new XmlTemplateEngine()
	def templateFile = new File(templateFileName)
	def output = engine.createTemplate(templateFile).make(bindings)
	def outputFile = new File(outputFileName)
	def parentFile = outputFile.getParentFile()
	if (parentFile != null)	parentFile.mkdirs()
	def fileWriter = new FileWriter(outputFile)

XML Template

<?xml version="1.0" encoding="UTF-8"?>
	<person type="${person.type}">

Java Properties

person.name=Riley MacBean


<?xml version="1.0" encoding="UTF-8"?>
	<person type="child">
		<name>Riley MacBean</name>

Leave a Reply

Your email address will not be published. Required fields are marked *