xmlgroovyxml-parsingconvertersxmlslurper

Groovy xml to map grouping duplicate keys


I have a xml response and i want it to be converted to a map but some xml nodes are duplicate so i want those to be converted to List of maps. Currently I'm using this code suggested in this post : xmlslurper-to-return-all-xml-elements-into-a-map

Thanks in advance.

Sample :

<head>test</head>
<tail>
    <name>1</name>
    <name>2</name>
</tail>
</body>

and I want the following map :

["head" : "test" , "tail" : [["name":"1"],["name":"2"]]]

Solution

  • After some struggling I wrote this code to solve my problem, I tried to use MultiValueMap either but it was converting all the values to list so Finally I had to write in on my own :

    def xml = new groovy.xml.XmlSlurper().parse(response)
    convertToMap(xml)
    
        def convertToMap(nodes) {
            def map = [:]
            nodes?.children()?.each {
                def key = it.name()
                def value = it.childNodes() ? convertToMap(it) : it.text()
                if (map.containsKey(key)) {
                    def currentValue = map.get(key)
                    if (currentValue instanceof List) {
                        currentValue.add(value)
                    } else {
                        map.put(key, [currentValue, value])
                    }
                } else {
                    map.put(key, value)
                }
            }
            map
        }