是否可以使用任意路径访问Xml节点?
例如:给定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>
如何使用以字符串形式提供的任意路径访问xml的内容 – 例如:
XmlSlurper xml = new XmlSlurper.parse(theXml) assert xml['bike.@name'] == 'Chopper' assert xml['car[0].country'] == 'Australia'
解决方法
一种方法是使用
the
Eval.x
static method来评估字符串;
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 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。