2017-03-01 50 views
0

我試圖用如下Groovy的鑄造XML NodeChildren爲byte []

<?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> 

下面來解析來自SOAP Web服務的XML響應我的Groovy代碼到XML響應轉換成所需的變量

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 

我想給signedDocument轉換爲byte[]如下

def document = signedDocument as byte[] 

但我得到以下異常

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

有人可以幫助這個mw嗎?

+0

你想幹什麼?該字符串表示該XML的字節[]? –

+0

@tim_yates是的,然後將其轉換爲文本文件 – RanPaul

回答

1

所以到節點轉換回字符串,然後得到的字符串的字節數,你可以這樣做:

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') 
+0

當我做'println'簽署的字符串=「+新字符串(signedDocumentBytes,'UTF-8')'看到' TUlNRS1WZXJzaW9uOiAxLjANCkRhdGU6IE1v'怎麼做我擺脫了''節點,並獲取節點內的文本? – RanPaul

+0

Errr'signedDocument.text()' –

+0

你能幫我解決這個問題嗎?https://stackoverflow.com/questions/47717505/groovy-create-a-map-with-jax-b-objects-specific-attributes – RanPaul