Created
December 11, 2015 17:10
-
-
Save nobeans/d385a33d9b42eab59dd8 to your computer and use it in GitHub Desktop.
XMLデータバインダ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import grails.databinding.SimpleDataBinder | |
import groovy.util.logging.Slf4j | |
/** | |
* XML文字列のタグ名の{@code snake_case}と{@code camelCase}を変換してから、対象オブジェクトにデータバインディングします。 | |
*/ | |
@Slf4j | |
class CaseConvertingXmlDataBinder { | |
void bind(Object object, String snakeCasedXml) { | |
log.debug "snake_cased XML: $snakeCasedXml" | |
def camelCasedXml = camelToSnakeForTagName(snakeCasedXml) | |
log.debug "camelCased XML: $camelCasedXml" | |
def parsedXml = new XmlSlurper().parseText(camelCasedXml) | |
new SimpleDataBinder().bind(object, parsedXml) | |
} | |
private static String camelToSnakeForTagName(String xml) { | |
xml.replaceAll(/<([^>]+?)>/) { tagName, all -> | |
tagName.replaceAll(/_(.)/) { it[1].toUpperCase() } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment