Dark theme | Light theme

December 9, 2009

Groovy Goodness: Type Conversion Using GPathResult When Reading XML

To read XML we can use the XmlSlurper class and we get a GPathResult object back. With GPathResult we can traverse throught the XML and get values from elements and attributes. GPathResult contains several method to convert values to specific classes, like toBoolean(), toString(), toInteger() and more.

def xml = '''
    <user loggedin="true">
        <fullname>Hubert A. Klein Ikkink</fullname>

def users = new XmlSlurper().parseText(xml)
def mrhaki = users.user[0]
assert mrhaki.@loggedin.toBoolean() 
assert 36 == mrhaki.age.toInteger()
assert 'mrhaki' ==
assert new URL('') == mrhaki.homepage.toURL()