0

I am trying to parse the XML response from soap webservice using as below

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <SignResult xmlns="http://www.tw.com/tsswitch">
      <Result>
        <Code>string</Code>
        <Desc>string</Desc>
      </Result>
      <SignedDocument>base64Binary</SignedDocument>
      <Archive>base64Binary</Archive>
      <Details>string</Details>
    </SignResult>
  </soap:Body>
</soap:Envelope>

Below is my groovy code to convert XML response to desired variables

def responseXML =  EntityUtils.toString(httpResponse.getEntity());

def signResponse = new XmlSlurper().parseText(responseXML)
def signedDocument = new XmlSlurper().parseText(responseXML).Body.SignResult.SignedDocument 
def resultCode = new XmlSlurper().parseText(responseXML).Body.SignResult.Result.Code 
def resultDesc = new XmlSlurper().parseText(responseXML).Body.SignResult.Result.Desc
def archive = new XmlSlurper().parseText(responseXML).Body.SignResult.Archive
def details = new XmlSlurper().parseText(responseXML).Body.SignResult.Details

I am trying to convert the signedDocument to byte[] as below

def document = signedDocument as byte[]

but am getting this below exception

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object with class 'groovy.util.slurpersupport.NodeChildren' to class 'byte'

Can someone help mw with this?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
OTUser
  • 3,788
  • 19
  • 69
  • 127

1 Answers1

1

So to convert the node back to a String, and then get the bytes for the string, you can do:

import groovy.xml.*

// Ignore namespaces, as otherwise we'll get tag0 namespaces added when we serialise
def signedDocument = new XmlSlurper(false, false).parseText(responseXML).'soap:Body'.SignResult.SignedDocument

// Convert to a string, then get the bytes in UTF-8
byte[] signedDocumentBytes = new StreamingMarkupBuilder()
    .bindNode(signedDocument)
    .toString()
    .getBytes('UTF-8')
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • when I do `println "signed string = "+new String(signedDocumentBytes , 'UTF-8')` am seeing `TUlNRS1WZXJzaW9uOiAxLjANCkRhdGU6IE1v` How Do I get rid of `` node and just get the text inside the node? – OTUser Apr 17 '17 at 21:13
  • Errr `signedDocument.text()` – tim_yates Apr 17 '17 at 21:44
  • can you please help me with this probelm https://stackoverflow.com/questions/47717505/groovy-create-a-map-with-jax-b-objects-specific-attributes – OTUser Dec 08 '17 at 19:38