vikki wiggi vikki wiggi - 1 year ago 104
Groovy Question

how to get the attribute value inside cdata from the response and use it in other request

  1. This is my response, how to get HIndex attribute value?

    <soap:Envelope xmlns:soap=""
    <HResponse xmlns="">
    <Hotel HIndex="1701" PrefContract="" HDIndex="28">
    <HNm> Demo</HNm>
    <Hotel HIndex="1702" PrefContract="" HDIndex="29">
    <HNm> Demo</HNm>
    <Hotel HIndex="1703" PrefContract="" HDIndex="30">
    <HNm> Demo</HNm>

  2. I want to use HIndex value in the other request.Am able to select the other node value but when am selecting attribute am getting ly the null value

Rao Rao
Answer Source

Here is the Script Assertion for the first request step. This will avoid additional groovy script step in the test case.

Please follow the appropriate comments in-line:

 * This is Script Assertion for the first
 * request step which extracts cdata from response,
 * then HIndex'es from extracted cdata. And
 * Assigns first value at test case level, so that
 * it can be used in the rest of the test steps of
 * the same test case.
 * */

* Closure to parse and retrieve the data
* retrieves element or attribute
def searchData = { data, item, itemType ->
    def parsedData = new XmlSlurper().parseText(data)
    if ('attribute' == itemType) {
        return parsedData?.'**'.findAll{it.@"$item".text()}*.@"$item"
    parsedData?.'**'.find { == item} as String

//Assert response xml
assert context.response, "Response data is empty or null"

//Get the CDATA from response which is inside of HResult
def cData = searchData(context.response, 'HResult', 'element')

//Assert retrieved CDATA is not empty
assert cData, "Data inside of HResult is empty or null"

//Get the HIndex list
def hIndexes = searchData(cData, 'HIndex', 'attribute')

//Print list of hIndexes hIndexes

//Print the first in the list "First HIndex is : ${hIndexes?.first()}"

//Print the last in the list "Last HIndex is : ${hIndexes?.last()}"

//Use the required HIndex from the list
context.testCase.setPropertyValue('HINDEX', hIndexes?.first().toString())
//or the below one using index
//context.testCase.setPropertyValue('HINDEX', hIndexes[0]?.toString())

In the following test steps, you can use the saved HINDEX in the following ways:

  • If the following step is request step (REST, SOAP, HTTP, JDBC etc), then use property expansion ${#TestCase#HINDEX} like <Index>${#TestCase#HINDEX}</Index>
  • If the following step is groovy script, then use one of the below:
    context.expand('${#TestCase#HINDEX}') or
    context.testCase.getPropertyValue('HINDEX') or

You can quickly try & execute the script from here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download