1

I am reading an XML file with a schema based on a Domain Class.

Here is a simple example for illustration (my current situation concerns a lot of fields from a lot of classes) :

class Player {
  String name
  Date birthDate
}

The XML file to read is :

<players>
<player name='P1' birthDate='12-09-1983'/>
</players>

So my question is: When parsing the XML file, I create Player instances with the following Groovy code:

def players = new XmlSlurper().parse(xmlFile)
players.player.each() {p ->
  new Player(name: p.@name, birthDate: p.@birthDate).save()
}

Is there another simpler way to do it ? Like params binding when creating/updating a domain object using code like new Player(params) or player.properties = params ?

fabien7474
  • 16,300
  • 22
  • 96
  • 124

1 Answers1

8

Actually, you can give directly the list of attributes to your domain class constructor with attributes().

def players = new XmlSlurper().parse(xmlFile)
players.player.each() {p ->
    new Player(p.attributes()).save()
}
rochb
  • 2,249
  • 18
  • 26