Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - Use XmlSlurper with a dynamic path

Tags:

groovy

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'
like image 424
Marty Pitt Avatar asked Dec 27 '22 10:12

Marty Pitt


1 Answers

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
}
like image 194
tim_yates Avatar answered Jan 06 '23 08:01

tim_yates