1
votes

I was working only with JSON response and for validation I was using below script. Now i need to do similar validation for XML response. How to achieve this for XML?

import groovy.json.JsonSlurper 

def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText response

assert json.name == "ABCD"
assert json.status == "Success"
1
Please show the sample xml response - Rao
Sorry Rao, As of now i dont have any response to share with you. Could you please take one simple example and share. - Basavaraj
There are lot of answer with that, see here - Rao
Thanks Rao, I will gothrough each link. - Basavaraj

1 Answers

2
votes

You can simply use XmlSlurper class that is very similar to JsonSlurper. Assuming this is your's XML, you can do something like this:

def xml = '''<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
  <food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
    <calories>650</calories>
  </food>
  <food>
    <name>Strawberry Belgian Waffles</name>
    <price>$7.95</price>
    <description>Light Belgian waffles covered with strawberries and whipped cream</description>
    <calories>900</calories>
  </food>
</breakfast_menu>
'''

def root = new XmlSlurper().parseText(xml)

assert root.food[0].name.text() == 'Belgian Waffles'

Keep in mind that new XmlSlurper().parseText(xml) returns a node that refers to the first (root) XML node element. Then you can do almost the same manipulations that are available for JsonSlureper class.