如何从Groovy';使用包含圆周线的字符串创建GPathResult

如何从Groovy';使用包含圆周线的字符串创建GPathResult,groovy,Groovy,如何做到这一点xml.elementA.elementB.每个{}都可以工作。我可以想出两种方法来解决这个问题 def elementPath = "elementA.elementB" xml."${elementPath}".each {} xml."elementA.elementB".each {} //用于测试的虚拟数据 def CAR_记录=“” 澳大利亚 速度为271公里/小时的生产皮卡车 马恩岛 最小的街道合法车辆,99厘米宽,59公斤重 法国 价值1500万美元的最有价值汽

如何做到这一点
xml.elementA.elementB.每个{}
都可以工作。

我可以想出两种方法来解决这个问题

def elementPath = "elementA.elementB"
xml."${elementPath}".each {}
xml."elementA.elementB".each {}
//用于测试的虚拟数据
def CAR_记录=“”
澳大利亚
速度为271公里/小时的生产皮卡车
马恩岛
最小的街道合法车辆,99厘米宽,59公斤重
法国
价值1500万美元的最有价值汽车
'''
def xml=new XmlSlurper().parseText(汽车记录)
def propNames='car.country'
//方法1
//将PropName拆分为各个属性,然后使用Inject遍历此列表
//将结果传递给下一个属性
propNames.split(/\./).inject(xml){obj,prop->obj?“$prop”}。每个{println it.text()}
//方法2
//构造一个字符串进行求值,并将xml对象传递给它(它被替换为x)
Eval.x(xml,“x.${propNames}”)。每个{println it.text()}

希望这有帮助:-)

// 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() }