Versions Compared

Key

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

...

Java has in-built support for DOM processing of XML using classes representing the various parts of XML documents, e.g. Document, Element, NodeList, Attr etc. For more information about these classes, refer to the respective JavaDocs. Some of the key classes are:

DOM class

JavaDocs

Element1.4 5

6 7

NodeList1.4 5

6 7

Groovy syntax benefits can be applied when using these classes resulting in code which is similar to but more compact than the Java equivalent. In addition, Groovy supports the following built-in helper method for these classes.

...

Code Block
import groovy.xml.DOMBuilder
import groovy.xml.dom.DOMCategory

messages = []

def processCar(car) {
    assert car.name() == 'car'
    def make = car.'@make'
    def country = car.country[0].text()
    def type = car.record[0].'@type'
    messages << make + ' of ' + country + ' has a ' + type + ' record'
}

def reader  = new StringReader(XmlExamples.CAR_RECORDS)
def doc     = DOMBuilder.parse(reader)
def records = doc.documentElement

use (DOMCategory) {
    assert 93 == records.'*'.size()
    def cars = records.'car'
    assert cars[0].parent() == records
    assert 3 == cars.size()
    assert 2 == cars.findAll{ it.'@year'.toInteger() > 1950 }.size()
    def carsByCentury = cars.list().groupBy{
        it.'@year'.toInteger() >= 2000 ? 'this century' : 'last century'
    }
    assert 1 == carsByCentury['this century'].size()
    assert 2 == carsByCentury['last century'].size()
    cars.each{ car -> processCar(car) }
}

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