Skip to: Site menu | Main content

Groovy 

      Download | Documentation | Developers | Community

An agile dynamic language for the Java Platform

Reading XML with Groovy and DOM Add comment to Wiki View in Wiki Edit Wiki page Printable Version

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 DOM with Groovy to read an existing XML file:

import javax.xml.parsers.DocumentBuilderFactory

messages = []

def processCar(car) {
    if (car.nodeName != 'car') return
    def make = car.attributes.getNamedItem('make').nodeValue
    def country = car.getElementsByTagName('country').item(0).firstChild.nodeValue
    def type = car.childNodes.find{'record' == it.nodeName}.attributes.getNamedItem('type').nodeValue
    messages << make + ' of ' + country + ' has a ' + type + ' record'
}

def builder     = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream = new ByteArrayInputStream(XmlExamples.CAR_RECORDS.bytes)
def records     = builder.parse(inputStream).documentElement

def cars = records.childNodes
(0..<cars.length).each{ processCar(cars.item(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'
]