Search

Dark theme | Light theme

December 18, 2009

Groovy Goodness: Getting Groovy with DOM

Reading XML is easy with Groovy's XmlParser, XmlSlurper classes. But sometimes we get an XML structure as DOM from another application or Java component. So we need more low-level access at the DOM level: we are in a world of nodes and elements. We can use the DOMCategory to make the low-level handling more Groovy.

import groovy.xml.*
import groovy.xml.dom.*

def xml = '''
<users>
    <user active="true">
        <fullname>mrhaki</fullname>
    </user>
    <user active="false">
        <fullname>Hubert A. Klein Ikkink</fullname>
    </user>
</users>
'''
def xmlDom = DOMBuilder.newInstance().parseText(xml)  // Create DOM structure.

def root = xmlDom.documentElement
use (DOMCategory) {
    def users = root.user
    assert 2 == users.size()
    
    assert 'User with fullname mrhaki is active' == userInfo(users[0])
    assert 'User with fullname Hubert A. Klein Ikkink is not active' == userInfo(users[1])

    assert 'mrhaki' == users.findAll { it.'@active'.toBoolean() }[0].fullname.text()
}

def userInfo(user) {
    def active = user.'@active'.toBoolean()
    def fullname = user.fullname.text()
    "User with fullname $fullname is ${active ? 'active' : 'not active'}"
}