使用 XmlSlurper 解析时如何使用带点的配置条目

How Can I Use Config Entries with Dots When Parsing with XmlSlurper

我正在尝试使用 groovy 配置条目来解析带有 XmlSlurper 的 xml 文件。

这是配置文件:

sample {
    xml {
        frompath = "Email.From"
    }
}

这是XML

<xml>
    <Email>
        <From>
            <Address>foo@bar.com</Address>
            <Alias>Foo Bar</Alias>
        </From>
    <Email>
</xml>

这是我最初尝试的:

XmlSlurper slurper = new XmlSlurper()

def record = slurper.parseText((new File("myfile.xml")).text)

def emailFrom = record?."${grailsApplication.config.sample.xml.frompath}".Address.text()

这不起作用,因为 XmlSlurper 允许在路径名中使用特殊字符,只要它们被引号括起来,所以应用程序将其翻译为:

def emailFrom = record?."Email.From".Address.text()

而不是

def emailFrom = record?.Email.From.Address.text()

我尝试将起始路径 属性 设置为 "Email"."From" 然后 '"Email"."From"'。我尝试在解析语句中间标记 属性(不要问。)

有人可以指点我一些资源以找出if/how我能做到吗?

我觉得这个 issue getting dynamic Config parameter in Grails taglib and this https://softnoise.wordpress.com/2013/07/29/grails-injecting-config-parameters/ 可能有解决方案的耳语,但我需要新的眼睛才能看到它。

issue getting dynamic Config parameter in Grails taglib 中的解决方案是取消引用此类路径的正确方法。例如

def emailFrom = 'Email.From'.tokenize('.').inject(record){ r,it -> r."$it" }
def emailFromAddress = emailFrom.Address.text()

如果您在那里的路径可能会变得复杂,并且您宁愿选择可能更危险的方式,您也可以使用 Eval。例如

def path = "a[0].b.c"
def map = [a:[[b:[c:666]]]] // dummy map, same as xmlslurper
assert Eval.x(map, "x.$path") == 666