I was writing code and I noticed some odd behavior in Groovy when I am dealing with XML and Maps. I thought about it and can\'t figure out why is it happening and should it
One thing that might help is, don't use GStrings for your keys. Groovy supports using objects directly as keys by wrapping them in parentheses.
From the manual:
Map keys are strings by default: [a:1] is equivalent to ["a":1]. But if you really want a variable to become the key, you have to wrap it between parentheses: [(a):1].
Fully working example:
def xml = '<xml><head>headHere</head><body>bodyHere</body></xml>'
Map map1 = [:]
def node = new XmlParser().parseText(xml)
node.each {
map1 << [ (it.name()): it.value() ]
}
println map1
println map1["head"]
println ">>>>>>>>>>>>>>>>>>>>>>"
Map map2 = [:]
map2 << ["head":"headHere"]
map2 << ["body":"bodyHere"]
println map2
println map2["head"]
println "<<<<<<<<<<<<<<<<<<<<<<"
def xml2 = '<xml><head>headHere</head><body>bodyHere</body></xml>'
Map map3 = [:]
def node2 = new XmlParser().parseText(xml2)
node2.each {
map3[it.name()] = it.value()
}
println map3
println map3["head"]
The output is:
[head:[headHere], body:[bodyHere]]
[headHere]
>>>>>>>>>>>>>>>>>>>>>>
[head:headHere, body:bodyHere]
headHere
<<<<<<<<<<<<<<<<<<<<<<
[head:[headHere], body:[bodyHere]]
[headHere]
Here is a demonstration of this quirk of double quoted strings in Groovy:
Double quoted strings are plain
java.lang.String
if there’s no interpolated expression, but aregroovy.lang.GString
instances if interpolation is present.
groovy:000> m = [:]
===> {}
groovy:000> tmp = "wat"
===> wat
groovy:000> key = "${tmp}"
===> wat
groovy:000> m << ["${key}": "hi"]
===> {wat=hi}
groovy:000> m["${key}"] = "hi"
===> hi
groovy:000> m
===> {wat=hi, wat=hi}
groovy:000> m["wat"] = "fuuuuuu!"
===> fuuuuuu!
groovy:000> m
===> {wat=hi, wat=fuuuuuu!}
groovy:000> m.keySet().each { println it.class }
class org.codehaus.groovy.runtime.GStringImpl
class java.lang.String
Enjoy ;)