首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Groovy将XML NodeChildren转换为byte[]

Groovy将XML NodeChildren转换为byte[]
EN

Stack Overflow用户
提问于 2017-03-02 02:29:16
回答 1查看 838关注 0票数 0

我正在尝试解析来自soap webservice的XML响应,如下所示

代码语言:javascript
复制
<?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>

下面是我将XML响应转换为所需变量的groovy代码

代码语言:javascript
复制
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[],如下所示

代码语言:javascript
复制
def document = signedDocument as byte[]

但是我得到了下面的异常

代码语言:javascript
复制
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object with class 'groovy.util.slurpersupport.NodeChildren' to class 'byte'

有人能帮我解决这个问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-02 05:00:00

因此,要将节点转换回字符串,然后获取字符串的字节数,您可以这样做:

代码语言:javascript
复制
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')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42539292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档