在 XmlSlurper 的 GPath 中使用变量 [英] Using variables in XmlSlurper's GPath

查看:24
本文介绍了在 XmlSlurper 的 GPath 中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让 XmlSlurper 通过变量获取任意元素?例如所以我可以做类似的事情输入文件:

Is there a way to have XmlSlurper get arbitrary elements through a variable? e.g. so I can do something like input file:

<file>
    <record name="some record" />
    <record name="some other record" />
</file>

def xml = new XmlSlurper().parse(inputFile)
String foo = "record"
return xml.{foo}.size()

我试过使用 {} 和 ${} 和 () 我如何转义这样的变量?还是没有办法?是否也可以使用闭包的结果作为参数?所以我可以做类似的事情

I've tried using {} and ${} and () how do I escape variables like that? Or isn't there a way? and is it possible to use results from closures as the arguments as well? So I could do something like

String foo = file.record
int numRecords = xml.{foo.find(/.w+$/)}

推荐答案

import groovy.xml.*

def xmltxt = """<file>
    <record name="some record" />
    <record name="some other record" />
</file>"""

def xml = new XmlSlurper().parseText(xmltxt)
String foo = "record"
return xml."${foo}".size()

这篇关于在 XmlSlurper 的 GPath 中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆