0

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

4

2 回答 2

2

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"
于 2011-08-27T16:19:18.800 回答
0

well, i ended up just using a multidimensional array, and that seems to have worked fine. Thanks again for your help

int i=0
String[][] friends = new String[test][4]
alum.connections.person.each{ conName ->
friends[i][0] =conName.'id'.toString()
friends[i][1] =conName.'first-name'.toString()
friends[i][2] =conName.'last-name'.toString()
friends[i][3] =conName.'picture-url'.toString()
i++
}
[Friends:friends]

This way, i was able to pass it on to my groovy page and iterate over the array

于 2011-08-27T23:16:35.937 回答