是否有一個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