Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

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

Include Page
XML Example
XML Example

Here is an example of using DOM with Groovy to read an existing XML file:

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