I'm trying to dynamically create a map collection but I am still new to grails and was hoping someone could help me. What I want to do is parse and xml file and add the values to a map. I've got the parsing down, but just dont know how to dynamically add the node values to the map. here's what i have so far:
example xml stream:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<connections total="29">
<person>
<id>123245</id>
<first-name>me</first-name>
<last-name>you</last-name>
</person>
</connections>
</person>
I then parse it like this:
def alum = new XmlSlurper().parseText(xmlResponse)
alum.connections.person.each{ conName ->
print conName.'id'.toString() + " " + conName.'first-name'.toString() + " " + conName.'last-name'.toString() + "\n"
}
So, this allows me to iterate over, and parse, the xml stream. my question is, if i wanted to add the values, dynamically, to a map like this:
def myMap= [fName:"SomeName", lName:"Sme last Name", id:1234]
how would i do this?
Thank you jason
If you don't know the child node names and want to use them as the keys in the map, use this:
def alum = new XmlSlurper().parseText(xmlResponse)
alum.connections.person.each { conName ->
def myMap = [:]
conName.children().each { child -> myMap[child.name()] = child.text() }
}
This will result in [id: '123245', 'first-name': 'me', 'last-name': 'you']
Unrelated: you can shorted up your debug code with a GString:
print "${conName.'id'} ${conName.'first-name'} ${conName.'last-name'}\n"