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:
-
tim
cat
dog
-
brenda
32
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:
-
a
21
-
b
-
c
1
2
field x