Groovy: dynamically create XML to collect objects with property sets

I have a set of fields with properties. Each property represents a single value or a set of objects (zero, one or more)

I need to create a tree like xml for it.

All the examples that I have found so far are either static or convert the map to xml. What is the correct way to add nodes to xml in a loop?

+1
source share
1 answer

You can do such things, but without any examples of your input and the desired output, all these are just blind guesses:

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' )
        }
      }
    }
  }
} )

What 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>

change

Still not sure what you have or want after your comment below, but this seems to fit 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>
+1
source

All Articles