How to get data from xml file using groovy? - groovy

Following groovy script is not working as expected.
def xml="<Collection><CustomerQuote><ID>99988877766</ID><TypeCode>2059</TypeCode><ApprovalStatusCode>4</ApprovalStatusCode></CustomerQuote><CustomerQuote><ID>99988877755</ID><TypeCode>2059</TypeCode><ApprovalStatusCode>4</ApprovalStatusCode></CustomerQuote></Collection>"
def completeXml= new XmlSlurper().parseText(xml);
def IDs = completeXml.Collection.CustomerQuote.findAll{node-> node.name() == 'ID' }*.text();
I am trying to copy all the ID value in xml in the IDs
Output
IDs[]
Expected Output
IDs[99988877766,99988877755]
I am not sure what i am doing wrong here.
Can anyone guide.
Thank you
Regards
Prat

The root node has to be omitted when using XmlSlurper, and you don't need to use findAll for this.
def xml="<Collection><CustomerQuote><ID>99988877766</ID><TypeCode>2059</TypeCode><ApprovalStatusCode>4</ApprovalStatusCode></CustomerQuote><CustomerQuote><ID>99988877755</ID><TypeCode>2059</TypeCode><ApprovalStatusCode>4</ApprovalStatusCode></CustomerQuote></Collection>"
def completeXml= new XmlSlurper().parseText(xml);
def IDs = completeXml.CustomerQuote.ID*.text();
Will output:
[
"99988877766",
"99988877755"
]
Try it in the Groovy Web Console

Related

Cannot replace string text in Groovy script

I am trying to replace a test in pom.xml using a groovy script. These are my two approaches. The text should be replaced is {env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}
Approach one
File mainPomXml = new File(rootDir,'/pom.xml')
mainPomXml.text.replace('{env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}','${env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}');
Approach two
def mainPomXml = new File(rootDir,'/pom.xml')
def mainPom = mainPomXml.text.replace('{env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}','${env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}');
mainPomXml.write(mainPom);
But none of these approaches work. That means both executes but the test is not get replaced. How to fix this issue?
Change the mainPom part as below.
def mainPomXml = new File(rootDir, '/pom.xml')
def mainPom = mainPomXml.text.replace('AM_SERVER_CREDS_USR', '${env.AM_'+ env.toUpperCase() +'_SERVER_CREDS_USR}')
mainPomXml.write(mainPom)

groovy extract value from string

I got a string from a server response:
responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"
then I do:
responseString[1..-2].tokenize(',')
got:
[""session":"vvSbMInXHRJuZQ=="", ""age":7200", ""prid":"901Vjmx9qenYKw"", ""userid":"user_1""]
get(3) got:
""userid":"user_1""
what I need is the user_1, is there anyway I can actually get it? I have been stuck here, other json methods get similar result, how to remove the outside ""?
Thanks.
If you pull out the proper JSON from responseStr, then you can use JsonSlurper, as shown below:
def s = 'responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"'
def matcher = (s =~ /responseString:"(.*)"/)
assert matcher.matches()
def responseStr = matcher[0][1]
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(responseStr)
assert "user_1" == json.userid
This code can help you get you to the userid.
def str= 'responseString:"{:"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1","hdkshfsd":"sdfsdfsdf"}'
def match = (str=~ /"userid":"(.*?)"/)
log.info match[0][1]
this pattern can help you getting any of the values you want from the string. Try replacing userid with age, you will get that
def match = (str=~ /"age":"(.*?)"/)
#Michael code is also correct. Its just that you have clarified that you want the user Name to be specific

Identifying multiple values in SOAP UI response with Groovy

I was recently helped through a problem here where I wanted to identify multiple values from a SOAPUI response. This was successfully answered here.
I tried to take this same approach to a new problem I have. This time I would like to pick up 4 values from each section to use as my expected results.
Below is an example of my response that I want to run the assert expected results against:
<ns1:LimitAndUsageDetailsList>
<ns2:LimitAndUsageDetails xmlns:ns2="http://www.">
<ns2:LimitCode>022</ns2:LimitCode>
<ns2:LimitCodeDesc>APPLIANCES</ns2:LimitCodeDesc>
<ns2:LimitType>N</ns2:LimitType>
<ns2:LimitBenefit>500.0</ns2:LimitBenefit>
<ns2:LimitBenefitUsed>0.0</ns2:LimitBenefitUsed>
<ns2:LimitBenefitAvailable>500.0</ns2:LimitBenefitAvailable>
<ns2:LimitBenefitService>0</ns2:LimitBenefitService>
<ns2:LimitBenefitUsedService>0</ns2:LimitBenefitUsedService>
<ns2:LimitBenefitAvailableService>0</ns2:LimitBenefitAvailableService>
<ns2:QualifyingPeriodIndicator/>
<ns2:ClaimIndicator>B</ns2:ClaimIndicator>
<ns2:LimitPeriod>1</ns2:LimitPeriod>
<ns2:LimitPeriodType>C</ns2:LimitPeriodType>
<ns2:LimitScale>INDIV</ns2:LimitScale>
</ns2:LimitAndUsageDetails>
<ns2:LimitAndUsageDetails xmlns:ns2="http://www.">
<ns2:LimitCode>023</ns2:LimitCode>
<ns2:LimitCodeDesc>NEBULISER</ns2:LimitCodeDesc>
<ns2:LimitType>N</ns2:LimitType>
<ns2:LimitBenefit>0.0</ns2:LimitBenefit>
<ns2:LimitBenefitUsed>0.0</ns2:LimitBenefitUsed>
<ns2:LimitBenefitAvailable>0.0</ns2:LimitBenefitAvailable>
<ns2:LimitBenefitService>1</ns2:LimitBenefitService>
<ns2:LimitBenefitUsedService>0</ns2:LimitBenefitUsedService>
<ns2:LimitBenefitAvailableService>1</ns2:LimitBenefitAvailableService>
<ns2:QualifyingPeriodIndicator/>
<ns2:ClaimIndicator>B</ns2:ClaimIndicator>
<ns2:LimitPeriod>3</ns2:LimitPeriod>
<ns2:LimitPeriodType>R</ns2:LimitPeriodType>
<ns2:LimitScale>INDIV</ns2:LimitScale>
</ns2:LimitAndUsageDetails>
And I am interested in LimitCode, LimitType, LimitPeriod and LimitPeriodType elements.
I have tried the following assert script but it doesnt work.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def holder = groovyUtils.getXmlHolder( messageExchange.responseContent )
def pxml = new XmlSlurper().parseText(context.response)
def expected = [
"022":"N":"1":"C"
'023':'N':'3':'R',
'030':'N':'1':'C',
]
def xml = new XmlSlurper().parseText(context.response)
def actual = xml.'**'.findAll{it.name() == 'LimitAndUsageDetails'}.collectEntries{[(it.LimitCode.text()): it.LimitType.text(): it.LimitPeriod.text(): it.LimitPeriodType.text()]}
assert expected == actual
Here is what you need to do.
Expected data requires couple more items as opposed to previous question.
So need to create map(to identify which data to what element)
Since there are list of details to be verified, expected data should be list of maps.
Please see the Script Assertion below:
assert context.response, 'Response is empty or null'
//list of maps; each map for single usage detail
//If the details are more, you may use a csv data file; solution may vary slightly
def expected = [
[ LimitCode: '022', LimitType: 'N', LimitPeriod: 1, LimitPeriodType: 'C'],
[ LimitCode: '023', LimitType: 'N', LimitPeriod: 3, LimitPeriodType: 'R']
]
 
 
def xml = new XmlSlurper().parseText(context.respone)
//Build the actual list of map from response
def actual = xml.'**'.findAll{it.name() == 'LimitAndUsageDetails'}.collect{ [
LimitCode : it.LimitCode.text(),
LimitType : it.LimitType.text(),
LimitPeriod : it.LimitPeriod.text() as Integer,
LimitPeriodType : it.LimitPeriodType.text()
]
}.sort {it.LimitCode}
assert expected == actual
You may quickly try the same online demo
You could use the below code which is also to get Response node values in
def groovyutils=new com.eviware.soapui.support.GroovyUtils(context)
def holder=groovyutils.getXmlHolder(messageExchange.responseContent)
holder.namespaces["ns"]="http://www.webserviceX.NET/"
def conversionRate=holder.getNodeValue("//ns:ConversionRateResult")
i was not able to test on your code since i dont have the correct namespace, but this code works perfectly fine for getting a value from response of currency convertor
you just need to change xpath inside getNodeValue and the namespace URL. this way its simpler

not able to extract attribute from xml in groovy script

I am trying to automate using groovy script. Here is my script. I am not able to mention namspace.
<ns2:contactPref xmlns="namespace 1" xmlns:ns2="name space 2">
<ns2:Information>
<value>Pass</value>
</ns2:Information>
<ns2:contactPreference>
<ns2:contactPointRel>
<contactPoint xs:type="Tele" xmlns:xs="namespace 3">
<cat>mob</cat>
<med>Int</med>
</contactPoint>
</ns2:contactPointRel>
</ns2:contactPreference>
</ns2:contactPref>
Now I want to fetch attribute at contactPoint tag
for this I have tried like this
groovyUtils=new com.eviware.soapui.support.Groovyutills(context)
def xPath=XPathFactory.newInstance().newXPath()
def type=context.expand('${GetResponse#Response#//*:contactPoint/#xs:type}')
log.info type
tried this
def type=context.expand('${GetResponse#Response#//*:contactPoint/#type}')
and I also tried this
def resp=groovyUtils.getXmlHolder("GetResponse#Response")
def type1=(String)xPath.evaluate('//:contactpoint/#xs:type',resp,xPathConstants.STRING)
but no help. please some one tell me how to do this??
try using this it should work
#{namespace 3}type
if you see xs:type="Tele" xmlns:xs="namespace 3" in contactPoint then xs which has value namespace 3 and {type} is Tele
Edited - You could use something like this - with xmlString as XML
def xml = new XmlSlurper().parseText(xmlString)
println
xml.contactPreference.contactPointRel.contactPoint."#{namespace
3}type"

Find an element in XML using XML Slurper

"I have a code that is working as expected but now I have to find the element in different format. Example is below
<car-load>
<car-model model="i10">
<model-year>
<year.make>
<name>corolla</name>
</year.make>
</model-year>
</car-model>
</car-load>
I have to find the value of "corolla" from this XML. Please reply.
You can run this in the Groovy console
def text = '''
<car-load>
<car-model model="i10">
<model-year>
<year.make>
<name>corolla</name>
</year.make>
</model-year>
</car-model>
</car-load>'''
def records = new XmlSlurper().parseText(text)
// a quick and dirty solution
assert 'corolla' == records.toString()
// a more verbose, but more robust solution that specifies the complete path
// to the node of interest
assert 'corolla' == records.'car-model'.'model-year'.'year.make'.name.text()

Resources