如何在Groovy for SoapUI中使用分隔符将所有SOAP响应值写入CSV文件

时间:2017-11-22 09:49:45

标签: xml csv groovy soapui

我是Groovy的新手,正在使用Soap UI。目前我正在研究Groovy模块,我需要在.csv文件中使用分隔符编写所有标记值。我从其他帖子获得的解决方案特定于xpath

但我正在努力实现以下目标:

  1. 要存储在csv文件中的所有重复数组的所有值
  2. 带有分隔符的单行中的每个数组
  3. 预期输出:

    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示例:

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

1 个答案:

答案 0 :(得分:0)

以下是同一个Soap Request步骤的Script Assertion,需要不需要才能使用其他Groovy脚本步骤。

脚本

 //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())