John Doe

Collect attributes and values ​​into a list of strings

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 cards like

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

      

and I am using, after you remove the data to 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'm doing something really bad, but I can't figure out what. I have tried several methods, but I get the same answer.

+3


source to share


1 answer


Try to find 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() ] 
}

      

+4


source







All Articles