Groovy - 使用带有动态路径的XmlSlurper [英] Groovy - Use XmlSlurper with a dynamic path
本文介绍了Groovy - 使用带有动态路径的XmlSlurper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:给定xml:
可以使用任意路径访问Xml的节点吗?
<记录>
< bike name ='Chopper'/>
< car name ='HSV Maloo'make ='Holden'year ='2006'>
< country>澳大利亚< / country>
< record type ='speed'>速度为271kph的生产卡车< / record>
< / car>
< car name ='P50'make ='Peel'year ='1962'>
< country>马恩岛< / country>
< record type ='size'> 99厘米宽,59公斤重的最小街车法< / record>
< / car>
< / records>
如何使用以字符串形式提供的任意路径访问xml的内容 - 例如:
$ p $
XmlSlurper xml = new XmlSlurper.parse(theXml)
assert xml ['bike。@ name'] = ='Chopper'
assert xml ['car [0] .country'] =='Australia'
解决方案
一种方法是使用 Eval.x
静态方法来评估一个字符串;
def xml ='''| <记录>
| < bike name ='Chopper'/>
| < car name ='HSV Maloo'make ='Holden'year ='2006'>
| <国家>澳大利亚和LT; /国家>
| < record type ='speed'>速度为271kph的生产卡车 | < /车>
| < car name ='P50'make ='Peel'year ='1962'>
| < country>马恩岛< / country>
| < record type ='size'> 99厘米宽,59公斤重的最小街车法< / record>
| < /车>
| < / records>'''。stripMargin()
//使我们的GPathResult
def slurper = new XmlSlurper()。parseText(xml)
/ /定义我们的测试
def tests = [
[query:'bike。@ name',expected:'Chopper'],
[query:'car [0] .country',expected :'澳大利亚']
]
//对于每个测试
tests.each {test - >
//断言我们得到预期的结果
assert Eval.x(slurper,x。$ test.query)== test.expected
}
Is it possible to access a node of Xml using an arbitary path?
Eg: Given the 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>
How do I access the contents of the xml using an arbitrary path, provided as a string -- eg:
XmlSlurper xml = new XmlSlurper.parse(theXml)
assert xml['bike.@name'] == 'Chopper'
assert xml['car[0].country'] == 'Australia'
解决方案
One method is to use the Eval.x
static method to evaluate a String;
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
}
这篇关于Groovy - 使用带有动态路径的XmlSlurper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文