如何在使用XmlSlurper进行分析时使用带有点的配置项 [英] How Can I Use Config Entries with Dots When Parsing with XmlSlurper
问题描述
这里是Config文件:
sample {
xml {
frompath =Email.From
}
}
这里是XML
< XML>
<电子邮件>
<来自>
<地址> foo@bar.com< /地址>
< Alias> Foo Bar< / Alias>
< / From>
<电子邮件>
< / xml>
这是我最初试过的:
<$ (新文件(myfile.xml))。text)
($ myfile.xml))
def record = slurper.parseText
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()
我试着将frompath属性设置为Email 。从
然后'Email。From'
。我尝试在解析语句中间标记属性(不要问)。
有人可以请我指点一些资源,以了解我/我可以如何做这个?
我觉得这样问题在Grails taglib中获得动态配置参数并且这个 https://softnoise.wordpress.com/2013/07/29/grails-injecting-config-parameters/ 可能会有一个解决方案的低语,但我需要新鲜的眼睛才能看到它。
def emailFrom ='Email.From'.tokenize('。')。inject(record){r,it - > r。$ it}
def emailFromAddress = emailFrom.Address.text()
如果你的路径可能变得复杂,而且你可能会采用更危险的方式,那么你也可以使用 Eval
。例如
def path =a [0] .bc
def map = [a:[[b: [c:666]]]] //虚拟地图,与xmlslurper相同
assert Eval.x(map,x。$ path)== 666
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.
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
这篇关于如何在使用XmlSlurper进行分析时使用带有点的配置项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!