我有一组带有属性的字段。每个属性是单个值或对象集合(null、一个或多个)
我需要为此创建一个像 xml 这样的树。
到目前为止,我发现的所有示例都是静态的或将地图转换为 xml。在循环中将节点添加到 xml 的正确方法是什么?
你可以做这种事情,但没有任何输入示例和所需输出,这一切都只是盲目的猜测:
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' )
}
}
}
}
} )
打印:
<?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>
在下面的评论之后仍然不确定您拥有或想要什么,但这似乎满足您的标准:
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 )
}
}
}
}
}
} )
并打印:
<?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>