Using a variable to extract value of property of a

2019-08-27 23:01发布

I am using SoapUI to test webservices. The following string (in xml format) is my request:

<Request>
   <AC>
      <AssetID>1</AssetID>
      <Asset_Name>ABC</Asset_Name>
      <Asset_Number>1</Asset_Number>
   </AC>
   <AC>
      <AssetID>2</AssetID>
      <Asset_Name>XYZ</Asset_Name>
      <Asset_Number>2</Asset_Number>
   </Ac>
</Request>

I am using the following code in a groovy script to extract value of Asset_Number for each AC (The above xml string is stored in variable strRequest):

def x = new XmlSlurper().parseText("$strRequest")

x.AC.each { AC ->
assetNum = AC."Asset_Number"
<<do something with the assetNum>>
}

However, I wish to parameterize the above code to pick up Asset_Number for various types of assets (e.g. AC, Peripheral etc). The request xml for each asset is in the same format as above. If I replace 'AC' with variable name 'requestName' in above code:

//strRequest = xml request
def requestName //I will pick up value for this from a test case property
def x = new XmlSlurper().parseText("$strRequest")

x.(requestName.toString()).each { requestName ->
    assetNum = requestName."Asset_Number"
    <<do something with the assetNum>>
}

it shows the following error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script166.groovy: 35: The current scope already contains a variable of the name requestName @ line 35, column 2. { ^ org.codehaus.groovy.syntax.SyntaxException: The current scope already contains a variable of the name requestName

I have tried a solution mentioned in another post Using a String as code with Groovy XML Parser, but it doesn't serve my purpose.

Any other ideas?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-27 23:17

You can use

x."$requestName".each
查看更多
爷、活的狠高调
3楼-- · 2019-08-27 23:24

Why XmlSlurper? In SoapUI you can use XmlHolder

import com.eviware.soapui.support.XmlHolder

def responseHolder = new XmlHolder(messageExchange.getResponseContentAsXml())

def resultFromResponse = responseHolder["here_is_your_xpath"]
assert someExpectedResult == resultFromResponse

And if you need to iterate via multiple xml nodes

resultFromResponse.each 
{
    assert result == resultFromResponse     
}
查看更多
登录 后发表回答