Santosh Nemani
Santosh Nemani

Reputation: 11

Getting attribute values from XML nodes with namespace in soapui using groovy

Below is my xml and i want to get the attribute value using groovy language so that i can use that in SoapUI assertion

<testns:TestResult attr1="100" attr2:"Sample">
  <testns:TestToken>XXXXXX</testns:TestToken>
</testns:TestResult>

I want to get the value of attr1 and attr2.

Upvotes: 1

Views: 1542

Answers (2)

Nilesh G
Nilesh G

Reputation: 103

As Guarav has correctly answered , one thing I would like to add. I think question is how to get values from XML when there are namespaces involved. Please refer sample code below

def holderRawReqToken = groovyUtils.getXmlHolder(response1.toString()) 
holderRawReqToken.declareNamespace('dns4','http://Yournamespaceurl') 
holderRawReqToken.declareNamespace('dns3','http://Yournamespaceurl') 
holderRawReqToken.declareNamespace('soapenv','http://schemas.xmlsoap.org/soap/envelope/') 
responseVaIdToken = holderRawReqToken.getNodeValue("/soapenv:Envelope[1]/soapenv:Body[1]/dns3:CreateTokenResponse[1]/dns4:tokenInformation[1]/dns4:tokenValue[1]/text()")

Upvotes: 0

Gaurav Khurana
Gaurav Khurana

Reputation: 3936

There are 2 problems in XML and its not valid

 attr2:"Sample" should be attr2="Sample"
 testns is not declared , it should be xmlns:testns="http://www.sample.com

So the correct XML is

     <testns:TestResult xmlns:testns="http://www.sample.com" attr1="100" attr2="Sample">
          <testns:TestToken>XXXXXX</testns:TestToken>
     </testns:TestResult>
Lets assume the name of this XML is **Request1**

so the groovy Code that can get the attribute is


def req=groovyUtils.getXmlHolder("Request1#Request")

def attr1=req.getNodeValue("//*:TestResult/@attr1")
log.info "Value of attr1 is " + attr1

def attr2=req.getNodeValue("//*:TestResult/@attr2")
log.info "Value of attr2 is " + attr2
The code which can get attribute is the xpath **//*:TestResult/@attr2**

if the XML is stored in response you can use Request1#Response instead of Request.

Additionally if you want to get value between tags use below code

 def testtoken=req.getNodeValue("//*:TestResult/*:TestToken")
 log.info "Value of testtoken is " + testtoken

enter image description here

Upvotes: 1

Related Questions