是否有一个grails插件或库可以将XML数据映射到Java类Object中?grails XML to Object绑定
我正在寻找一些将xml数据映射到Java类字段的groovy类。
--- UPDATE -----
以下的Grails服务类尝试做这个映射,但它不工作。
会有人提示如何纠正下面的代码,使其工作?
感谢
class DataBinderService {
boolean transactional = false
def grailsApplication
private BeanWrapper wrapper = new BeanWrapperImpl()
public List bindAllXmlData (Class targetClass, GPathResult source, List properties) {
if (targetClass == null || source == null || properties == null) return null
def resultList = []
def className = WordUtils.uncapitalize(targetClass.simpleName)
source[className]?.each {
def boundObj = bindXmlData(targetClass, it, properties)
System.out.println(boundObj)
resultList.add(boundObj)
}
return resultList
}
public Object bindXmlData (Class targetClass, GPathResult source, List properties) {
if (targetClass == null || source == null || properties == null) return null
def targetObject = grailsApplication.classLoader.loadClass(targetClass.name).newInstance()
if (targetObject) {
return bindXmlData(targetObject, source, properties)
} else {
return null
}
}
public Object bindXmlData (Object target, GPathResult source, List properties) {
if (target == null || source == null || properties == null) return null
wrapper.registerCustomEditor (Date.class, new CustomDateBinder())
wrapper.setWrappedInstance(target)
properties.each {String property ->
if (property.contains('.')) {//This indicates a domain class to bind e.g. experiment.id -> Experiment
def propertyName = property.tokenize('.')
def id = source[propertyName[0]]["@${propertyName[1]}"]?.toString()
if (id != null) {
def subdomainInstance = null
try {subdomainInstance = grailsApplication.classLoader.loadClass("edu.kit.iism.experimentcenter.${WordUtils.capitalize(propertyName[0])}").get(id)} catch (Exception ex) {}
if (subdomainInstance != null) wrapper.setPropertyValue(propertyName[0], subdomainInstance)
}
} else if (property.equals('id')) { //The id property is set as an attribute rather than text
def id = source['@id']?.toString()
if (id != null) wrapper.setPropertyValue(property, id)
} else { //regular attributes
def prop = source[property]?.toString()
if (prop != null) wrapper.setPropertyValue(property, prop)
}
}
return target
}
}
Groovy的'XMLSlurper'是不够的? – Grooveek
它不是通用和通用的。我们需要手动解析xml并保存到Java对象。对?我需要的是一个通用的方法来自动绑定一个Java类与XML数据 – othman
我已经更新了OP。有一个班我尝试做绑定。但它不起作用。 – othman