0

I have an XML like below.

xml1 = '''
<?xml version="1.0" encoding="UTF-8"?>
<soap>
    <group1>
        <g1node1>g1value1</g1node1>
        <g1node2>g1value2</g1node2>
        <g1node3>g1value3</g1node3>
    </group1>
    <group2 attr="attrvalue1">
        <g2node1>g2value1</g2node1>
        <g2node2>g2value2</g2node2>
        <g2node3>g2value3</g2node3>
    </group2>
</soap>
'''

Here, i need to get all the xml node and its values as output, either as line by line result and as a list with groovy. The output should look like

g1node1 = g1value1
g1node2 = g1value2
... and so on...

or either with a groovy map like below

out = [g1node1 : "g1value1", g1node2 : "g1value2", ...and so on...]

can anyone help me how to achieve this with groovy code?

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
mmar
  • 1,840
  • 6
  • 28
  • 41

1 Answers1

0

I would still like to know (as Tim mentioned) what you have tried yet, but here is my itch:

def result = new XmlSlurper().parseText( xml )
result.'**'.collectEntries { !it.childNodes() ? [ it.name(), it.text() ] : [:] }
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • I am new to groovy and i have tried like below. I googled and find out the keyword 'collectEntries'. But could not get to what i need. xml1 = new File("C:\\junk\\a.txt").text def xmlParser = new XmlParser() out = xmlParser.parseText(xml1) out.'**'.collectEntries{ println it.text() } and i got the below exception and i know the code is wrong. g1value1g1value2g1value3g2value1g2value2g2value3 Exception thrown java.lang.NullPointerException at ConsoleScript62.run(ConsoleScript62:6) – mmar May 23 '14 at 21:46
  • **@dmahapatro** Thanks for your time and help. I tried your code and it works and the result shows like below > [g1node1:g1value1, g1node2:g1value2, g1node3:g1value3, g2node1:g2value1, g2node2:g2value2, g2node3:g2value3] I have 2 questions. 1. Is it possible to have the values in (double quotes) ""?. 2. When i execute the same code in SoapUI (its my automation tool), i get an nullpointer exception on the line where i use "out.'**'.collectEntries {..." can you please help me? – mmar May 23 '14 at 21:47