Loading...

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 = '''
<users>
    <user loggedin="true">
        <age>36</age>
        <name>mrhaki</name>
        <fullname>Hubert A. Klein Ikkink</fullname>
        <homepage>http://www.mrhaki.com/</homepage>
    </user>
</users>
'''

def users = new XmlSlurper().parseText(xml)
def mrhaki = users.user[0]
assert mrhaki.@loggedin.toBoolean() 
assert 36 == mrhaki.age.toInteger()
assert 'mrhaki' == mrhaki.name.toString()
assert new URL('http://www.mrhaki.com/') == mrhaki.homepage.toURL()