如何使用包含 perioid 的字符串从 Groovy 的 GPathResult 中检索元素 [英] How can I retrieve an element from Groovy's GPathResult using a string that contains a perioid

查看:20
本文介绍了如何使用包含 perioid 的字符串从 Groovy 的 GPathResult 中检索元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def elementPath = "elementA.elementB"
xml."${elementPath}".each {}

如何进行这项工作?xml.elementA.elementB.each {} 有效.

How to make this work? xml.elementA.elementB.each {} works.

推荐答案

我能想到 2 种方法来解决这个问题...

I can think of 2 ways round this...

// Dummy Data for the testing
def CAR_RECORDS = '''
    <records>
      <car name='HSV Maloo' make='Holden' year='2006'>
        <country>Australia</country>
        <record type='speed'>Production Pickup Truck with speed of 271kph</record>
      </car>
      <car name='P50' make='Peel' year='1962'>
        <country>Isle of Man</country>
        <record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>
      </car>
      <car name='Royale' make='Bugatti' year='1931'>
        <country>France</country>
        <record type='price'>Most Valuable Car at $15 million</record>
      </car>
    </records>
  '''
def xml = new XmlSlurper().parseText( CAR_RECORDS )
def propNames = 'car.country'

// METHOD 1
// Split the propnames into individual properties, then use Inject to walk down this list
// Passing the result to the next property
propNames.split( /./ ).inject( xml ) { obj, prop -> obj?."$prop" }.each { println it.text() }

// METHOD 2
// Construct a string to evaluate, and pass the xml object to it (it gets substituted in place of x)
Eval.x( xml, "x.${propNames}" ).each { println it.text() }

Eval.x 的 javadoc 页面在这里

希望这有帮助:-)

这篇关于如何使用包含 perioid 的字符串从 Groovy 的 GPathResult 中检索元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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