My first (useful) script in Groovy

We had a large number of XML files to modify and found that Groovy with its GPath syntax was the right tool. Here is an example that takes a (simplified) XML file and changes the value of one attribute for a subset of nodes.

<?xml version="1.0"?>
<variable id="V1" visible="true" />
<variable id="V2" visible="false" />
<variable id="V3" visible="false" />

And the script to change all XML files in the current directory.
I found it easier to write and debug it than using a mix of java and XSL.

def basedir = new File( ".")

// Create a directory for patched files
new File("patched").mkdir()

// Get files with ".xml" extension
files = basedir.listFiles().grep(~/.*\.xml$/)

// Iterate on the files
files.each {

def patchXML(file) {
println "-------------------"
println "Patching $file.name"

def design = new XmlParser().parse(file)
def modified = false

for (variable in design.process.variable) {
switch (variable.@id) {
case "V1":
case "V2":
if (variable.@visible == "false") {
variable.@visible = "true"
modified = true
if (modified) {
new File("patched/$file.name").withPrintWriter() {
new XmlNodePrinter(it).print(design)
println "Patched $file.name is in \"patched\" directory"
} else {
println "$file.name was not modified"
println "-------------------"

Aucun commentaire: