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.
Groovy
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 = [:] props.propertyNames().each{prop-> bindings[prop]=props.getProperty(prop) } // 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) fileWriter.write(output.toString()) fileWriter.close() }
XML Template
<?xml version="1.0" encoding="UTF-8"?> <output> <person type="${person.type}"> <name>${person.name}</name> <age>${person.age}</age> <role>${person.role}</role> </person> </output>
Java Properties
person.type=child person.name=Riley MacBean person.age=1 person.role=son
Result
<?xml version="1.0" encoding="UTF-8"?> <output> <person type="child"> <name>Riley MacBean</name> <age>1</age> <role>son</role> </person> </output>