Skip to content

Instantly share code, notes, and snippets.

@fumokmm
Created March 15, 2011 15:39
Show Gist options
  • Save fumokmm/870894 to your computer and use it in GitHub Desktop.
Save fumokmm/870894 to your computer and use it in GitHub Desktop.
This gist is fork from https://gist.github.com/870666 by @kyon_mm (This gist is used at http://d.hatena.ne.jp/fumokmm/20110315/1300210292)
class KeyValue {
def key
def value
KeyValue(key, value){
this.key = key
this.value = value
}
}
def convert(def builder, List list, boolean first = true) {
if (first) {
builder.langs(type: 'current') {
convert(builder, list, false)
}
} else {
list.each { kv ->
if (kv.value instanceof List)
builder."${kv.key}" {
convert(builder, kv.value, false)
}
else
builder."${kv.key}"(kv.value)
}
}
}
def sw = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(sw)
xml.doubleQuotes = true // 属性はダブルクォートだよね!
def list = [
new KeyValue("key1","value1"),
new KeyValue("key2","value2"),
new KeyValue("key3", [
new KeyValue("key3-1","value3-1"),
new KeyValue("key3-2","value3-2")
])
]
def expect = '''\
<langs type="current">
<key1>value1</key1>
<key2>value2</key2>
<key3>
<key3-1>value3-1</key3-1>
<key3-2>value3-2</key3-2>
</key3>
</langs>'''
convert(xml, list)
assert sw.toString() == expect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment