javaxmlgroovyxml-parsingxmlslurper

API xml response looping and extract all the element values - Groovy


Below is the snapshot of my API XML response

<Plaintiff>
  <PlaintiffName>SEB B.A.
  </PlaintiffName>
  <PlaintiffName>SEB??
  </PlaintiffName>
</Plaintiff>

I want to extract all the PlaintiffName under the Plaintiff node.

Code:

String caseResponseText = response.getResponseText()
def xmlResult = new XmlSlurper().parseText(caseResponseText)
def plaintiff = xmlResult.Case.Plaintiff.PlaintiffName[0].text()

The above one i got the result of first plaintiff name / second plaintiff name. But how should i looping thru this node and get all the palintiff value dynamically?

Because response may have only one plaintiff or more than one, so I need to parse dynamically and get all the values thru looping


Solution

  • Simply loop over the nodes:

    def plaintiffs = xmlResult.Case.Plaintiff.PlaintiffName
    for (plaintiff in plaintiffs) {
        // do something with plaintiff
    }