Groovy - Use XmlSlurper with a dynamic path

Is it possible to access node Xml using a harsh path?

For example: given 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 to access the contents of xml using an arbitrary path represented as a string - for example:

 XmlSlurper xml = new XmlSlurper.parse(theXml) assert xml[' bike.@name '] == 'Chopper' assert xml['car[0].country'] == 'Australia' 
+4
source share
1 answer

One method is to use the static Eval.x method to evaluate 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 } 
+9
source

Source: https://habr.com/ru/post/1382714/


All Articles