Groovy-将XmlSlurper与动态路径一起使用
是否可以使用任意路径访问Xml节点 例如:给定xml:Groovy-将XmlSlurper与动态路径一起使用,groovy,Groovy,是否可以使用任意路径访问Xml节点 例如:给定xml: <records> <bike name='Chopper' /> <car name='HSV Maloo' make='Holden' year='2006'> <country>Australia</country> <record type='speed'>Production Pickup Tru
<records>
<bike name='Chopper' />
<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>
</records>
一种方法是用来计算字符串
def xml = '''| <records>
| <bike name='Chopper' />
| <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>
| </records>'''.stripMargin()
// Make our GPathResult
def slurper = new XmlSlurper().parseText( xml )
// Define our tests
def tests = [
[ query:'bike.@name', expected:'Chopper' ],
[ query:'car[0].country', expected:'Australia' ]
]
// For each test
tests.each { test ->
// assert that we get the expected result
assert Eval.x( slurper, "x.$test.query" ) == test.expected
}
defxml=''''|
|
|
|澳大利亚
|速度为271公里/小时的生产皮卡车
|
|
|马恩岛
|最小的街道合法车辆,99厘米宽,59公斤重
|
|''.stripMargin()
//让我们的GPathResult
def slurper=new XmlSlurper().parseText(xml)
//定义我们的测试
def测试=[
[查询:'bike.@name',应为'Chopper'],
[查询:'car[0]。国家/地区',应为'Australia']
]
//每次测试
tests.each{test->
//断言我们得到了预期的结果
assert Eval.x(slurper,“x.$test.query”)==test.expected
}
事实上,尽管这很酷,但我真的不明白为什么会这样——特别是Eval中的令牌$test
和query
。为什么$test
而不是${test}
)?另外,query
是否是针对GPathResult
定义的方法?如果不是,它来自哪里?@MartyPitttest
来自我们的每个函数,因此第一次循环它等于map[查询:'bike.@name',预期:'Chopper']
。因此,“x.$test.query”
(与“x.${test.query}”
)将被计算为字符串“x.bike.@name”
Eval.x
将x
设置为slurper
实例,然后对表达式求值。然后,它对我们列表中的第二个地图再次执行相同的操作[查询:'car[0].country',预期:'Australia']
。。。希望这能解释吗?是的,非常清楚。昨晚一定很晚了!再次感谢。
def xml = '''| <records>
| <bike name='Chopper' />
| <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>
| </records>'''.stripMargin()
// Make our GPathResult
def slurper = new XmlSlurper().parseText( xml )
// Define our tests
def tests = [
[ query:'bike.@name', expected:'Chopper' ],
[ query:'car[0].country', expected:'Australia' ]
]
// For each test
tests.each { test ->
// assert that we get the expected result
assert Eval.x( slurper, "x.$test.query" ) == test.expected
}