gpt4 book ai didi

Groovy - 将 XmlSlurper 与动态路径结合使用

转载 作者:行者123 更新时间:2023-12-02 06:39:37 27 4
gpt4 key购买 nike

是否可以使用任意路径访问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
}

关于Groovy - 将 XmlSlurper 与动态路径结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8243593/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com