Skip to content

Instantly share code, notes, and snippets.

@nobeans
Created March 15, 2011 16:29
Show Gist options
  • Save nobeans/870977 to your computer and use it in GitHub Desktop.
Save nobeans/870977 to your computer and use it in GitHub Desktop.
map2xml.groovy
String map2xml(Map input) {
def sw = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(sw)
builder.doubleQuotes = true
builder.metaClass.recursive = { Map map ->
map.each { key, value ->
"${key}"(value in Map ? { recursive(value) } : value)
}
}
builder.langs(type: "current") {
recursive input
}
sw.toString()
}
def input = [
key1: "value1",
key2: "value2",
key3: [
"key3-1": "value3-1",
"key3-2": "value3-2",
]
]
def expected = '''\
<langs type="current">
<key1>value1</key1>
<key2>value2</key2>
<key3>
<key3-1>value3-1</key3-1>
<key3-2>value3-2</key3-2>
</key3>
</langs>'''
def result = map2xml(input)
assert result == expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment