Xml – Get the number of occurrences of a given node in a soap request using soapUI

groovysoapsoapuiweb servicesxml

I am working on mock web service requests. Given a web service request below, how can I determine the number of occurrences of the "ns3:data" element using Groovy? Thanks.

<ns1:foo>
    <ns3:data>
        <ns3:CustomerNumber>123</ns3:CustomerNumber>
    </ns3:data>
    <ns3:data>
        <ns3:CustomerNumber>456</ns3:CustomerNumber>
    </ns3:data>
</ns1:foo>

I tried the following, but it doesn't work.

def req = new XmlSlurper().parseText(mockRequest.requestContent)
def numberOfPayments = req.depthFirst()​.findAll { it.name() == 'Payment'}

Best Answer

You can use XmlHolder from SOAPUI to count the number of nodes.

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def holder = groovyUtils.getXmlHolder("SOAPService#Request")
holder.namespaces['ns3'] = "namespace corresponding to ns3 goes here"

def numberOfData = holder["count(ns://data)"]

where SOAPService represents the service you are invoking. Refer how to count nodes for details.

Using XmlSlurper (assuming namespace ns1 and ns3 is declared):

def xml = """
<ns1:foo xmlns:ns1="dummy" xmlns:ns3="dummy2">
    <ns3:data>
        <ns3:CustomerNumber>123</ns3:CustomerNumber>
    </ns3:data>
    <ns3:data>
        <ns3:CustomerNumber>456</ns3:CustomerNumber>
    </ns3:data>
</ns1:foo>
"""

def req = new XmlSlurper().parseText(xml)
def numberOfPayments = req.data.size()

assert numberOfPayments == 2
Related Topic