Search code examples
groovy

XmlSlurper to return all xml elements into a map


I have the following groovy code:

def xml = '''<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<foot>
    <email>[email protected]</email>
    <sig>hello world</sig>
</foot>
</note>'''

def records = new XmlSlurper().parseText(xml)

How do I get records to return a map looks like the following:

["to":"Tove","from":"Jani","heading":"Reminder","body":"Don't forget me this weekend!","foot":["email":"[email protected]","sig":"hello world"]]

Thanks.


Solution

  • You can swing the recursion weapon. ;)

    def xml = '''<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
    <foot>
        <email>[email protected]</email>
        <sig>hello world</sig>
    </foot>
    </note>'''
    
    def slurper = new XmlSlurper().parseText( xml )
    
    def convertToMap(nodes) {
        nodes.children().collectEntries { 
            [ it.name(), it.childNodes() ? convertToMap(it) : it.text() ] 
        }
    }
    
    assert convertToMap( slurper ) == [
        'to':'Tove', 
        'from':'Jani', 
        'heading':'Reminder', 
        'body':"Don't forget me this weekend!", 
        'foot': ['email':'[email protected]', 'sig':'hello world']
    ]