我以为可以在Android项目的gradle构建脚本中用Kotlin替换groovy,这样我就可以开始学习Kotlin了,但是我遇到的第一个问题是试图寻找可以替代XmlSlurper和MarkupBuilder的类或库。有人可以建议要使用的图书馆或类(class)吗?

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 = [email protected]()
            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)
            }
        }
    }

最佳答案

对于MarkupBuilder,您可以使用withGroovyBuilder方法,因此可以肯定地执行以下操作来开始构建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
    }
}
我不太记得常规的用法,所以我无法真正帮助其他人。从XmlSlurper遍历条目看起来很麻烦。如果您只是将配置存储在这些XML文件中,建议您切换到JSON或HOCON。读和写这些会容易得多;)

关于groovy - Kotlin替代groovy XmlSlurper和MarkupBuilder,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44298051/

10-10 04:29