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

与世无争的帅哥 提交于 2019-12-24 13:14:57

问题


I'm trying to use a groovy Config entry to parse an xml file with XmlSlurper.

Here's the Config file:

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

Here's the XML

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

This is what I tried initially:

XmlSlurper slurper = new XmlSlurper()

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

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

This doesn't work because XmlSlurper allows one to use special characters in path names as long as they're surrounded by quotes, so the app is translating this as:

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

and not

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

I tried setting the frompath property to be "Email"."From" and then '"Email"."From"'. I tried tokenizing the property in the middle of the parse statement (don't ask.)

Can someone please point me towards some resources to find out if/how I can do this?

I feel like this issue getting dynamic Config parameter in Grails taglib and this https://softnoise.wordpress.com/2013/07/29/grails-injecting-config-parameters/ may have whispers of a solution, but I need fresh eyes to see it.


回答1:


The solution in issue getting dynamic Config parameter in Grails taglib is a proper way to deref down such a path. E.g.

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

If your path there can get complex and you rather go with the potentially more dangerous way, you could also use Eval. E.g.

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


来源:https://stackoverflow.com/questions/28175103/how-can-i-use-config-entries-with-dots-when-parsing-with-xmlslurper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!