Groovy: dynamically create XML for collection of objects with collections of properties

前端 未结 1 1960
故里飘歌
故里飘歌 2021-01-07 08:03

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

1条回答
  •  有刺的猬
    2021-01-07 08:35

    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
      
    
    

    edit

    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
      
    
    

    0 讨论(0)
提交回复
热议问题