将 XML 导入 Grails 域类 [英] Import XML into a Grails Domain Class
问题描述
我正在读取具有基于域类的架构的 XML 文件.
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
}
要读取的 XML 文件是:
The XML file to read is :
<players>
<player name='P1' birthDate='12-09-1983'/>
</players>
所以我的问题是:解析 XML 文件时,我使用以下 Groovy 代码创建 Player 实例:
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()
}
还有其他更简单的方法吗?像使用 new Player(params)
或 player.properties = params
之类的代码创建/更新域对象时的参数绑定一样吗?
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
?
推荐答案
实际上,您可以使用 attributes() 将属性列表直接提供给域类构造函数.
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()
}
这篇关于将 XML 导入 Grails 域类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!