例如:给定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 testsdef tests = [ [ query:'bike.@name',expected:'Chopper' ],[ query:'car[0].country',expected:'Australia' ]]// For each testtests.each { test -> // assert that we get the expected result assert Eval.x( slurper,"x.$test.query" ) == test.expected}总结
以上是内存溢出为你收集整理的Groovy – 将XmlSlurper与动态路径一起使用全部内容,希望文章能够帮你解决Groovy – 将XmlSlurper与动态路径一起使用所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)