3

I have xml data looking like this:

<persons>
  <person key="M">John Doe</person>
  <person key="N">Jane Doe</person>
</persons>

I want to collect them into a list of maps like

[[key: M, name: John Doe], [key: N, name: Jane Doe]]

and I use, after slurping the data into the variable 'p', using XmlSlurper:

p.collect { [key: it.@key.text(), name it.text()] }

but I get

[[key: MN, name: John DoeJane Doe]]

Obviously I do something very wrong, but I can't figure out what. I have tried a number of methods but get the same answer.

serafim
  • 75
  • 1
  • 1
  • 9

1 Answers1

4

Try looking for children() from root node.

def xml = """
<persons>
  <person key="M">John Doe</person>
  <person key="N">Jane Doe</person>
</persons>
"""

def slurper = new XmlSlurper().parseText( xml )

assert [
    [key:'M', name:'John Doe'], 
    [key:'N', name:'Jane Doe']
] == slurper.children().collect { 
    [ key: it.@key.text(), name: it.text() ] 
}
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • 2
    This solved it AND a couple of follow up questions. Stackoveflow turns out to be more informative than all the documentation I've read. – serafim Aug 26 '14 at 05:56