Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Include Page
GROOVY:XML Example
GROOVY:XML Example

Here is an example of using DOM reading an existing XML file with Groovy and StAX:

Code Block
// requires stax.jar and stax-api.jar
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'
]