I have a collection of fields with properties. Each property is a single value or a collection of objects (either null, one or many)
I need to create a tree like xml
You can do this sort of thing, but without any examples of your input, and desired output it's all just blind guesswork:
import groovy.xml.*
def collection = [
[ name:'tim', pets:['cat','dog'], age:null ],
[ name:'brenda', pets:null, age:32 ]
]
def process = { binding, element, name ->
if( element[ name ] instanceof Collection ) {
element[ name ].each { n ->
binding."$name"( n )
}
}
else if( element[ name ] ) {
binding."$name"( element[ name ] )
}
}
println XmlUtil.serialize( new StreamingMarkupBuilder().with { builder ->
builder.bind { binding ->
data {
collection.each { e ->
item {
process( binding, e, 'name' )
process( binding, e, 'pets' )
process( binding, e, 'age' )
}
}
}
}
} )
That prints:
<?xml version="1.0" encoding="UTF-8"?><data>
<item>
<name>tim</name>
<pets>cat</pets>
<pets>dog</pets>
</item>
<item>
<name>brenda</name>
<age>32</age>
</item>
</data>
Still not sure what you have or want after your comment below, but this seems to fullfil your criteria:
import groovy.xml.*
def process = { binding, element, name ->
if( element[ name ] instanceof Collection ) {
element[ name ].each { n ->
binding."$name"( n )
}
}
else if( element[ name ] ) {
binding."$name"( element[ name ] )
}
}
class Form {
List fields
}
// Create a new Form object
f = new Form( fields:[ [ name:'a', val:21 ], [ name:'b' ], [ name:'c', val:[ 1, 2 ], x:'field x' ] ] )
// Serialize it to XML
println XmlUtil.serialize( new StreamingMarkupBuilder().with { builder ->
builder.bind { binding ->
data {
f.fields.each { fields ->
item {
fields.each { name, value ->
process( binding, fields, name )
}
}
}
}
}
} )
and prints:
<?xml version="1.0" encoding="UTF-8"?><data>
<item>
<name>a</name>
<val>21</val>
</item>
<item>
<name>b</name>
</item>
<item>
<name>c</name>
<val>1</val>
<val>2</val>
<x>field x</x>
</item>
</data>