Groovy – 将XmlSlurper与动态路径一起使用
发布时间:2020-12-14 16:26:30 所属栏目:大数据 来源:网络整理
导读:是否可以使用任意路径访问Xml节点? 例如:给定xml: records bike name='Chopper' / car name='HSV Maloo' make='Holden' year='2006' countryAustralia/country record type='speed'Production Pickup Truck with speed of 271kph/record /car car name='P
是否可以使用任意路径访问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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |