Reputation: 53
I am a newbee to Groovy, am trying to print the below output using Groovy but I was unable to fetch the Zone values from the below XML.
I try to use .each and save the offercode into a list and print the values but I could not able to do the same with Zone. Could you please guide me on this.
Here is XML:
<ns8:Offers>
<ns8:Offer>
<ns8:offerDetails>
<offerCode>6789</offerCode>
<offerCategory>ABCED</offerCategory>
<offerType>
<Value>Promo</Value>
<Language>E</Language>
</ns8:offerDetails>
<ns8:offerZones>
<ns8:zone>Zone 1</ns8:zone>
<ns8:zone>Zone 2</ns8:zone>
<ns8:zone>Zone 3</ns8:zone>
<ns8:zone>Zone 4</ns8:zone>
</ns8:offerZones>
</ns8:Offer>
<ns8:Offer>
<ns8:offerDetails>
<offerCode>12345</offerCode>
<offerCategory>ABCED</offerCategory>
<offerType>
<Value>Promo</Value>
<Language>E</Language>
</ns8:offerDetails>
<ns8:offerZones>
<ns8:zone>Zone 1</ns8:zone>
<ns8:zone>Zone 2</ns8:zone>
<ns8:zone>Zone 3</ns8:zone>
<ns8:zone>Zone 4</ns8:zone>
</ns8:offerZones>
</ns8:Offer>
<ns8:Offer>
<ns8:offerDetails>
<offerCode>12345</offerCode>
<offerCategory>ABCED</offerCategory>
<offerType>
<Value>Promo</Value>
<Language>E</Language>
</ns8:offerDetails>
</ns8:Offer>
</ns8:Offers>
Expected Output: Offer code is :6789 and Offer Zone are:Zone 1,Zone 2,Zone 3,Zone 4
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.text.SimpleDateFormat
import com.eviware.soapui.support.XmlHolder
def QuerySubscriberResponse = context.expand( '${QuerySubscriber#Response}' )
def queryxml = new XmlSlurper().parseText(QuerySubscriberResponse)
def nbaofferscode=[];
def nbaOffersZone=[];
queryxml.Body.querySubscriberResponse.profferOffers.profferOffer.each{ nbaofferss ->
nbaofferscode.add(nbaofferss.offerDetails.offerCode)
}
log.info nbaofferscode
Upvotes: 0
Views: 541
Reputation: 527
You have a few problems in your example.
<ns8:offerDetails>
elements have missing closing tags.It looks like your GPath is expecting the XML to be embedded in a web page.
In this example I've added the missing </ns8:offerDetails>
closing tags and loaded the XML from a file.
file = new File( 'NestedXml.xml')
def queryxml = new XmlParser(false,false)
.parse( file )
def nbaofferscode=[];
def nbaOffersZone=[];
queryxml.each { offer ->
offer.'ns8:offerZones'.'ns8:zone'.each { zone ->
nbaOffersZone << zone.text()
}
nbaofferscode << offer.'ns8:offerDetails'.offerCode.text()
}
println nbaofferscode
println nbaOffersZone
Running the above script gives this output:
[6789, 12345, 12345]
[Zone 1, Zone 2, Zone 3, Zone 4, Zone 1, Zone 2, Zone 3, Zone 4]
The third offer doesn't contain any zones.
Upvotes: 1