Skip to content

Instantly share code, notes, and snippets.

@aalmiray
Created March 12, 2011 22:15
Show Gist options
  • Save aalmiray/867629 to your computer and use it in GitHub Desktop.
Save aalmiray/867629 to your computer and use it in GitHub Desktop.
Xml2Groovy
import groovy.swing.SwingBuilder
import groovy.beans.Bindable
@Singleton
class Xml2Groovy {
String parseText(String text) {
def root = new XmlSlurper().parseText(text)
ByteArrayOutputStream baos = new ByteArrayOutputStream()
IndentPrinter printer = createIndentPrinter(baos)
walkXml(printer, root)
printer.flush()
baos.toString()
}
private IndentPrinter createIndentPrinter(OutputStream os) {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os))
new IndentPrinter(pw)
}
private void walkXml(IndentPrinter printer, node) {
printer.printIndent()
printer.print(node.name())
if(node.attributes()) {
printer.print('(')
String attrs = node.attributes().collect([]) { e ->
"${e.key}: $e.value"
}.join(', ')
printer.print(attrs)
printer.print(')')
}
if(node.children().size()) {
printer.println(' {')
printer.incrementIndent()
for(child in node.children()) walkXml(printer, child)
printer.decrementIndent()
printer.printIndent()
printer.println('}')
} else {
printer.println('')
}
}
}
@Bindable class Model {
String value
}
xml = '''
<frame title="'Xml Test'" pack="true" visible="true">
<gridLayout cols="1" rows="3"/>
<textField id="'input'" columns="20"
text="bind('value', target: model)"/>
<textField id="'output'" columns="20" editable="false"
text="bind{model.value}"/>
<button text="'Click Me!'"
actionPerformed="{model.value = 'clickety click'}"/>
</frame>
'''
gs = new GroovyShell()
script = gs.parse(Xml2Groovy.instance.parseText(xml))
swing = new SwingBuilder()
swing.model = new Model()
swing.edt {
build(script)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment