Reading XML with Groovy and XOM

This example assumes the following class is already on your CLASSPATH:

XmlExamples.groovy
class XmlExamples {
  static def CAR_RECORDS = '''
    <records>
      <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>
      <car name='Royale' make='Bugatti' year='1931'>
        <country>France</country>
        <record type='price'>Most Valuable Car at $15 million</record>
      </car>
    </records>
  '''
}

Here is an example of using XOM with Groovy to process an existing XML file:

// require(groupId:'xom', artifactId:'xom', version:'1.1')
import nu.xom.Builder

def reader   = new StringReader(XmlExamples.CAR_RECORDS)
def records  = new Builder().build(reader).rootElement
messages = []

def processCar(car) {
    def make = car.getAttribute('make').value
    def country = car.getFirstChildElement('country').value
    def type = car.getFirstChildElement('record').getAttribute('type').value
    messages << make + ' of ' + country + ' has a ' + type + ' record'
}

def cars = records.childElements
(0..<cars.size()).each{ processCar(cars.get(it)) }

assert messages == [
    'Holden of Australia has a speed record',
    'Peel of Isle of Man has a size record',
    'Bugatti of France has a price record'
]
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.