通过 Groovy 中的键检索地图中的值

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']

我被上面的代码烦了快一天了。我不明白为什么我无法通过 map['ust1twastool01a'].

获取值

我附上了控制台的屏幕截图,它显示地图不为空但无法通过键获取其值。 map2 只是控制组,因为它具有类似的结构,将字符串映射为键并将列表映射为值

使用如下:

map.put(node.@ServerName.text(), list)

附带说明一下,我相信您可以将代码简化为:

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