Search code examples
groovygroovyshellgroovy-console

Retrieve value in map by key in Groovy


def text= '''<Rollback>  <Kits>
<Kit ServerName='ust1twastool01a'>
  <Backup>2016-10-18_20_34-46-_server-21.000.409_client-21.000.407.zip</Backup>
  <Backup>2016-10-18_21_57-33-_server-21.000.409_client-21.000.407.zip</Backup>
  <Backup>2016-10-19_02_40-03-_server-21.000.413_client-21.000.407.zip</Backup>
  <Backup>2016-10-19_13_58-36-_server-21.000.413_client-21.000.407.zip</Backup>
  <Backup>2016-10-20_03_14-34-_server-21.000.413_client-21.000.407.zip</Backup>
</Kit>
<Kit ServerName='another_server'>
  <Backup>123123.zip</Backup>
  <Backup>321321.zip</Backup>
</Kit>
</Kits></Rollback>'''


def xml = new XmlSlurper().parseText(text)
def map = [:]
i = 0
xml.Kits.Kit.each{node->
    def list = []
    node.Backup.each{kit->
    list.add(kit)
}
map.put(node.@ServerName, list)
}

print map // print map with all keys and values

// Somehow, it's not working ...
print map['ust1twastool01a']

def map2 = ['1':["abc","123"], '2':["bcd", "456"]]
print map2['1']

​ I have been annoyed by the above code for almost the day. I don't understand why I can't get value by map['ust1twastool01a'].

I attached a screenshot from a console, it shows that map is not empty but just can't get its value by key. map2 is just control group as it has the similar structure to map string as key and list as valueenter image description here


Solution

  • Use as below:

    map.put([email protected](), list)
    

    On a side note, I believe you can simplify the code to just:

    def xml = new XmlSlurper().parseText(text)
    def map = xml.Kits.Kit.collectEntries { node -> 
        [ [email protected](), node.Backup.collect() ] 
    }