Versions Compared

Key

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

...

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

Code Block
import javax.xml.parsers.DocumentBuilderFactory
import
org.w3c.dom.Node

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 factory     = DocumentBuilderFactory.newInstance()
def builder     = factory.newDocumentBuilder()
def bytes       = XmlExamples.CAR_RECORDS.bytes
def inputStream = new ByteArrayInputStream(bytes)
def doc         = builder.parse(inputStream)
def records     = doc.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'
]