SD31 SD31 - 11 months ago 128
Groovy Question

How to write all the SOAP response values into CSV file with delimiter in Groovy for SoapUI

I am new to Groovy and working on Soap UI. Currently I am working on Groovy module, where I need to write the all tag values with delimiter on to

.csv
file. The solution I got from other post is specific to
xpath
.

But am trying to achieve the below:


  1. all the values of all the repetitive arrays to be stored in csv file

  2. each array in single row with delimiter



Expected Output:

code;Name;Category;Manufacturer;Price;Stock // as header
1234;product name;some category;manufacturer;100;1
1235;product name2;some category2;manufacturer2;1002;2


XML sample:

<ns2:personalarray1Response>
<ns2:personarray1>
<Code>1234</Code>
<Name>product name</Name>
<Category>some category</Category>
<Manufacturer>manufacturer</Manufacturer>
<Price>100</Price>
<Stock>1</Stock>
</ns2:personarray1>
<ns2:personarray1>
<Code>1235</Code>
<Name>product name2</Name>
<Category>some category2</Category>
<Manufacturer>manufacturer2</Manufacturer>
<Price>1002</Price>
<Stock>2</Stock>
</ns2:personarray1>
<ns2:personarray1>
<Code>1234</Code>
<Name>product name</Name>
<Category>some category</Category>
<Manufacturer>manufacturer</Manufacturer>
<Price>100</Price>
<Stock>1</Stock>
</ns2:personalarray1>
</ns2:personalarray1Response>

Rao Rao
Answer Source

Here is the Script Assertion for the same Soap Request step and need not require to use additional Groovy script step.

Script

 //Change file name as needed
def fileName = '/file/path/to.csv'
def delimiter = ',' 

assert context.response, 'Response is empty or null'

def xml = new XmlSlurper().parseText(context.response)

def personalInfos = xml.'**'.findAll { it.name() == 'personarray1' }


//Create the list of data (person array) 
def list = personalInfos.collect {info -> info.children()*.name().collectEntries{[(it): info."$it"] } }


def sb = new StringBuffer(list[0].keySet().join(delimiter))
sb.append('\n')

list.collect { sb.append(it.values().join(delimiter)).append('\n')}
log.info "Data going to be written into file: \n ${sb.toString()}"

new File(fileName).write(sb.toString())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download