1
votes

SoapUI with Groovy I am using SoapUI pro and groovy script. I am reading the customers record from request into the following,

def CustRec = context.expand('${GetProductPriceOffer#Request#/tem:request[1]/quot:Customers[1]}' )

the value in CustRec is,

<quot:Customers>
<quot:Person>
<quot:CustomerType>PRIMARY</quot:CustomerType>
<quot:Sequence>0</quot:Sequence>
</quot:Person>
<quot:Person>
<quot:CustomerType>ADULT</quot:CustomerType>
<quot:Sequence>1</quot:Sequence>
</quot:Person>
</quot:Customers>

Now I want to count the total number of Person objects in Customers (i.e. answer is 2 in this scenario). I tried with while loop but it did not work for me. Can anyone tell how can I achieve using the loops?

Thanks in advance

1
Show the code for your while loop. - SiKing
Your groovy snippet specifies to only get one record from the Customers. Is that the snippet you're using before the loop, or did you modify it? - Josh Edwards
I did not modify anything. - Srini

1 Answers

1
votes

To count all the occurrences of <Person> inside <Customers> you can use count xpath function as follows:

def numPersons =
context.expand('${GetProductPriceOffer#Request#count(//*:Customers/*:Person)}')

Another possibility is to use XmlSlurper instead of using xpath, with it you can count the occurrences of <Person>, but if you need to do more operations you can manipulate the Xml in a easy way. To count the <Person> you can use the follow approach:

def custRec = context.expand('${GetProductPriceOffer#Request}')
// parse the request
def xml = new XmlSlurper().parseText(custRec)
// find all elements in xml which tag name it's Person
// and return the list
def persons = xml.depthFirst().findAll { it.name() == 'Person' }
// here you've the number of persons
log.info persons.size()

Hope this helps,