简体   繁体   中英

Kotlin replacement for groovy XmlSlurper & MarkupBuilder

I thought i would replace groovy with Kotlin in our gradle builds scripts for our Android project so i could start learning Kotlin but the first problem i ran into was trying to hunt down some classes or libraries that could replace XmlSlurper & MarkupBuilder. Can someone suggest a library or class to use?

def entries = new XmlSlurper().parse("${projectDir}/src/release/res/values/app_settings.xml")
    def fileLocation = "${projectDir}/src/debug/res/xml/env_prod.xml"
    println "XML file location = ${fileLocation}"
    def writer = new FileWriter(new File(fileLocation))
    def xmlOut = new MarkupBuilder(writer)
    xmlOut.mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
    xmlOut.Environment {
        entries.string.each {
            def name = it.@name.toString()
            def body = it.text()
            if (name.startsWith('default_')) {
                // don't copy production omniture when we're doing local testing!
                name = name.replace('default_', '').toUpperCase()
                xmlOut.entry(['name' : name], body)
            }
        }
    }

For MarkupBuilder you can use withGroovyBuilder method, so you could definitely do something like this for starting to build Environment :

val xmlOut = MarkupBuilder(writer)
xmlOut.mkp.xmlDeclaration(mapOf("version" to "1.0", "encoding" to "utf-8"))
xmlOut.withGroovyBuilder {
    "Environment"() {
     // the logic would go here
    }
}

I can't remember groovy all too well so I can't really help with the rest. Iterating over entries from XmlSlurper looks problematic. If you are simply storing your config in these XML files, I'd suggest switching to JSON or HOCON. Reading and writing to these would be a lot easier ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM