Groovy – 将XmlSlurper与动态路径一起使用

Groovy – 将XmlSlurper与动态路径一起使用,第1张

概述是否可以使用任意路径访问Xml节点? 例如:给定xml: <records> <bike name='Chopper' /> <car name='HSV Maloo' make='Holden' year='2006'> <country>Australia</country> <record type='speed'>Production 是否可以使用任意路径访问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 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与动态路径一起使用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1228143.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存