Generate CDATA inside of tag using StreamingMarkupBuilder

一世执手 提交于 2019-12-10 18:25:15

问题


I need following structure in XML

<DCS>
    <bytes length="29235"><![CDATA[....]]></bytes>
</DCS>

And have following code

DCS {
bytes(length: "${docBytes.size()}",mkp.yieldUnescaped("<![CDATA[${docBytes}]]>"))
}

But it generate

   <DCS>
    <![CDATA[[....]]]>
<bytes length='135948'>groovy.xml.streamingmarkupsupport.StreamingMarkupWriter@32adca00</bytes>
    </DCS>

How can I generate required xml structure ? Thanks in advance.


回答1:


You need to put your mkp.yieldUnescaped in a closure, not just as the second parameter to the bytes tag method, ie:

import groovy.xml.*

byte[] docBytes = 'Tim Yates'

new StreamingMarkupBuilder().bind {
  DCS {
    bytes( length:docBytes.length ) {
      mkp.yieldUnescaped "<![CDATA[${docBytes.toList().join(' ')}]]>"
    }
  }
}

Which generates:

<DCS><bytes length='9'><![CDATA[84 105 109 32 89 97 116 101 115]]></bytes></DCS>

You can see here, I've encoded each byte into a String separated by a space. How you do it is up to you (and I guess depends on what is going to be decoding the bytes) ;-)



来源:https://stackoverflow.com/questions/12929060/generate-cdata-inside-of-tag-using-streamingmarkupbuilder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!