Search code examples
listgroovyxmlslurpercollect

collect attributes and values into string list


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: [email protected](), 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.


Solution

  • 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: [email protected](), name: it.text() ] 
    }