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

时间:2011-11-23 14:10:42

标签: groovy

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

1 个答案:

答案 0 :(得分:10)

一种方法是使用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
}