Skip to: Site menu | Main content

Groovy 

      Download | Documentation | Developers | Community

An agile dynamic language for the Java Platform

Reading XML with Groovy and StAX 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 reading an existing XML file with Groovy and StAX:

// require(groupId:'stax', artifactId:'stax-api', version:'1.0.1')
// require(groupId:'stax', artifactId:'stax', version:'1.2.0')
import javax.xml.stream.*

messages = []
currentMessage = ''

def processStream(inputStream) {
    def reader
    try {
        reader = XMLInputFactory.newInstance()
            .createXMLStreamReader(inputStream)
        while (reader.hasNext()) {
            if (reader.startElement)
                processStartElement(reader)
            reader.next()
        }
    } finally {
        reader?.close()
    }
}

def processStartElement(element) {
    switch(element.name()) {
        case 'car':
            currentMessage = element.make + " of "
            break
        case 'country':
            currentMessage += element.text() + " has a "
            break
        case 'record':
            currentMessage += element.type + " record"
            messages << currentMessage
            break
    }
}

class StaxCategory {
    static Object get(XMLStreamReader self, String key) {
        return self.getAttributeValue(null, key)
    }
    static String name(XMLStreamReader self) {
        return self.name.toString()
    }
    static String text(XMLStreamReader self) {
        return self.elementText
    }
}

def bytes = XmlExamples.CAR_RECORDS.bytes
def inputStream = new ByteArrayInputStream(bytes)
use (StaxCategory) { processStream(inputStream) }

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'
]