0
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 只是控制组,因为它具有将字符串映射为键并将列表映射为值的类似结构在此处输入图像描述

4

1 回答 1

2

使用如下:

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() ] 
}
于 2016-10-20T18:48:10.147 回答