jaxb生成cdata块

1、需要添加一个适配器:

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class AdapterCDATA extends XmlAdapter<String, String>
{

    @Override
    public String marshal(String arg0) throws Exception
    {
        return "<![CDATA[" + arg0 + "]]>";
    }

    @Override
    public String unmarshal(String arg0) throws Exception
    {
        return arg0;
    }

}

 

2、之后在jaxb的模型中添加注解:

@XmlJavaTypeAdapter(AdapterCDATA.class)
protected String id;

 

3、最后在marshaller上设置属性转换特殊字符串:

marshaller.setProperty("com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler",
      new CharacterEscapeHandler(){
           @Override
           public void escape(char[] ch, int start,
                int length, boolean isAttVal,
                   Writer writer) throws IOException
                {
                     writer.write(ch, start, length);
                }
     });

 

完成,测试。

 

posted @ 2015-11-19 18:01  demonrain  阅读(2347)  评论(2编辑  收藏  举报